Is there a magic method for calling an attribute as a method in php?

7

For example, we have the class:

class foo
{
var $bar = 1;
}

I wanted to know if I can do something if I call it like this:

$foo = new foo;
$foo->bar();
    
asked by anonymous 08.09.2016 / 14:35

1 answer

12

The magic method __call does this.

See:

class Foo {

      protected $bar;

      public function __call($method, $arguments) {
           return isset($this->$method) ? $this->$method : null;
      }
 }

What is the __call ?

The __call method will perform an action when you call a method of a class that is not declared or is inaccessible (for example, protected and private ).

You must always 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 array ).

Recommendations

I would recommend you keep a pattern to use such "magic features". For example, you always detect whether the method you tried to call starts with the word get .

See:

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 class Foo , the return value would be different, since the method exists (and is a public method), then __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 keyword var , since in PHP version 5 you entered the keywords of visibility public , protected and private , when declaring the visibility of a method .

    
08.09.2016 / 14:37