Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__get() example via Zandstra

Matt Zandstra gives the following example in his text "PHP Objects Patterns and Practice" to illustrate the __get() method:

class Person {
    function __get( $property ) {
        $method = "get{$property}";
        if ( method_exists( $this, $method ) ) {
            return $this->$method();
        }
    }
    function getName() {
        return "Bob";
    }
    function getAge() {
        return 44;
    }
}

In reality, we know we would never actually create such methods (getName and getAge) to return such static values, but instead - we would create name and age properties in the object and return those using the $this operator.

My question is whether this example actually shows utility. And if it does not, could somebody provide a better example of why one would use __get() for the same sort of purpose?

Justification for asking

If we were to use name and age properties in the object, then the __get() function would not be fired anyway, because attempting to get these properties with:

$person = new Person();
$name = $person->name;

would cause either the name property to actually be returned if it were public, or cause a visibility error if it were private or protected. The __get() function would not be executed in either of these 'real' cases... am i missing something?

I'm fully aware that the above code works. I am not convinced that it is a practical example.

like image 829
Jordan Arseno Avatar asked Mar 21 '26 07:03

Jordan Arseno


1 Answers

You are absolutely right - I am impressed that you are quoting from a book, that example just plain sucks.

Using the magic __get method to call methods is just wrong, there are other magic methods just for that kind of usage:

  • __call()
  • __callStatic()
  • __invoke()

__get() and __set() should be used to read and write non declared object properties.

like image 188
Alix Axel Avatar answered Mar 23 '26 20:03

Alix Axel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!