PHP magic __call method
Lesson 3: PHP Magic Methods
Today we're going to dive into one of my favorite Php magic methods, the Php __call Magic method.
Imagine being able to call any method with any number of parameters on an instance of a class...
Well guess what, you can!
Magic __call method parameters
The PHP magic __call method accepts two arguments.
$method
$parameters
__call($method, $parameters)
The $method variable
Is a string
Is the name of the actual method that was called.
The $parameters variable
Is an array
The array is filled with the parameters passed to the method that was called.
Another way to think about $method is like this:
$building->$method($parameters)
$building->height($parameters)
$method = "height"
$building->floors($parameters)
$method = "floors"
$building->windows($parameters)
$method = "windows"
Another way to think about $parameters is like this:
$building->$method($parameters)
$building->$method("one", "two", "three")
$parameters = ["one", "two", "three"]
$building->$method(1)
$parameters = [1]
$building->$method()
$parameters = []
Together you can think about the magic __call method like this.
$building->height("one", "two", "three")
$method = "height"
$parameters = ["one", "two", "three"]
$building->floors(1)
$method = "floors"
$parameters = [1]
$building->windows()
$method = "windows"
$parameters = []
In this Clean Code Studio screencast we'll use the magic call method to dynamically call and execute PHP functions at run time as well as access private, normally inaccessible, private methods on a PHP class .