phpmagic-methods

Practical applications of PHP magic methods - __get, __set, and __call


I've generally tried to stay away from PHP's magic methods because they seem to obfuscate an object's public interface. That said, they seem to be used more and more, at least, in the code I've read, so I have to ask: is there any consensus on when to use them? Are there any common patterns for using these three magic methods?


Solution

  • __call()

    I've seen it used to implement behaviors, as in add extra functions to a class through a pluginable interface.

    Pseudo-code like so:

    $method = function($self) {};
    $events->register('object.method', $method);
    $entity->method(); // $method($this);
    

    It also makes it easier to write mostly similar functions, such as in ORMs. e.g.:

    $entity->setName('foo'); // set column name to 'foo'
    

    __get()/__set()

    I've mostly seen it used to wrap access to private variables.

    ORMs are the best example that comes to mind:

    $entity->name = 'foo'; // set column name to 'foo'