Question:
For example, we have the class:
class foo
{
var $bar = 1;
}
I wanted to know if there is a way to execute something if I call it like this:
$foo = new foo;
$foo->bar();
Answer:
The __call
magic method does this.
Look:
class Foo {
protected $bar;
public function __call($method, $arguments) {
return isset($this->$method) ? $this->$method : null;
}
}
What is __call
for?
The __call
method will perform an action when you call a method of a class that is not declared or is inaccessible ( protected
and private
, for example).
It is always necessary to declare two parameters for this function: The first is the name of the method you tried to invoke, and the second, the arguments passed (these are stored in an array
).
recommendations
I would recommend that you maintain a standard for utilizing such "magical features". For example, you always detect if the method you tried to call starts with the word get
.
Look:
class Foo {
protected $bar = 'bar';
public function __call($method, $arguments) {
if (substr($method, 0, 3) == 'get')
{
$prop = strtolower(substr($method, 3));
return $this->$prop;
}
throw new \BadMethodCallException("Method $method is not defined");
}
}
So when you access the getBar
method, you would get the value of $bar
.
$foo = new Foo;
$foo->getBar(); // Retorna 'bar'
Note : If we had declared the public method bar
in the Foo
class, the return value would be different, as the method exists (and is a public
method), so __call
would not be invoked.
public function bar() {
return 'Valor do método, não da propriedade';
}
addition
It is highly recommended not to use the var
keyword, since PHP version 5 introduced the public
, protected
and private
visibility keywords when declaring the visibility of a method.