PHP Get Magic Method

Posted on

What is does

The get magic method is called if the property that you are requesting does not exist on the class.

Why would you use it

Similar to call() and callStatic() if the property you are looking for does not exist this is called instead, in here you can add logic such as;

$someClass = new SomeClass();
$someClass->aProperty;

public function __get( $key )
{        
    return 'no property found for ' . $key
    //returns “no property found for aProperty"
}

Other uses for this are retrieving properties that you may have in an array on the model, like Laravel’s eloquent.

$someClass = new SomeClass();
$someClass->name;

class foo {
    protected $values = array('name' => 'joe', age => 28);

    public function __get( $key )
    {
        return $this->values[ $key ];
        // returns “joe"
    }
}