Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
Major Productions Avatar asked May 12 '11 14:05

Major Productions


2 Answers

__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'
like image 89
Denis de Bernardy Avatar answered Sep 28 '22 00:09

Denis de Bernardy


The main reason is that you do not need to type as much. You could use them for, say, an ORM record and act as implicit setters/getters:

using __call():

$user = new User();
$user->setName("Foo Bar");
$user->setAge(42);
$user->save();

using __set():

$user->name = "Foo Bar";
$user->age = 42;

which maps to a simple array:

array(
    "name" => "Foo Bar",
    "age"  => 42
)

It is much easier to write such an array to the database than doing a lot of manual calls to collect all needed information. __set() and __get() have another advantage over public members: You are able to validate/format your data.

like image 44
jwueller Avatar answered Sep 27 '22 23:09

jwueller