7
For example, we have the class:
class foo
{
var $bar = 1;
}
I was wondering if you could run something if I called it that:
$foo = new foo;
$foo->bar();
7
For example, we have the class:
class foo
{
var $bar = 1;
}
I was wondering if you could run something if I called it that:
$foo = new foo;
$foo->bar();
12
The magical method __call does that.
Behold:
class Foo {
      protected $bar;
      public function __call($method, $arguments) {
           return isset($this->$method) ? $this->$method : null;
      }
 }
__call?The method __call will perform an action when you call a method from a class that is not declared or 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 past arguments (these are stored in a array).
I would recommend you maintain a standard for using such "magic features". For example, you always detect if the method you tried to call starts with the word get.
Behold:
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 accessed the method getBar, you would get the value of $bar.
  $foo = new Foo;
  $foo->getBar(); // Retorna 'bar'
Note: If we had declared the public method bar in class Foo, the value returned would be different because the method exists (and is a method public), then __call would not be invoked.
  public function bar() {
      return 'Valor do método, não da propriedade';
  }
It is highly recommended not to use the keyword var, since in version 5 of PHP was to introduce the visibility keywords public, protected and private, when declaring the visibility of a method.
Not only undeclared methods, but for inaccessible methods as well, i.e., if the instance calls a protected or private method will also fall into the __call
Thank you for reminding.
Good answer! + 1
Browser other questions tagged php
You are not signed in. Login or sign up in order to post.
And what the purpose of calling a property as a method?
– Neuber Oliveira
A magician never reveals his tricks
– Bernardo Kowacic
@Neuberoliveira makes perfect sense, the question is valid. Frameworks like Laravel do this, and it’s good to "demystify" this for him (my answer). When you use a Pattern called
Fluent Interface, can be fully valid do as the AP is asking.– Wallace Maxters
@Bernardokowacic say I then was Mister M...
– Wallace Maxters
Mister W, the magician upside down.
– Maniero
@Bigown glad it’s not "Mister Catra"
– Wallace Maxters
In fact what I meant was what he intended to do with it, to know his scenario and what problem he intends to solve with it.
– Neuber Oliveira