phpmagic-function

When do/should I use __construct(), __get(), __set(), and __call() in PHP?


A similar question discusses __construct, but I left it in my title for people searching who find this one.

Apparently, __get and __set take a parameter that is the variable being gotten or set. However, you have to know the variable name (eg, know that the age of the person is $age instead of $myAge). So I don't see the point if you HAVE to know a variable name, especially if you are working with code that you aren't familiar with (such as a library).

I found some pages that explain __get(), __set(), and __call(), but I still don't get why or when they are useful.


Solution

  • This page will probably be useful. (Note that what you say is incorrect - __set() takes as a parameter both the name of the variable and the value. __get() just takes the name of the variable).

    __get() and __set() are useful in library functions where you want to provide generic access to variables. For example in an ActiveRecord class, you might want people to be able to access database fields as object properties. For example, in Kohana PHP framework you might use:

    $user = ORM::factory('user', 1);
    $email = $user->email_address;
    

    This is accomplished by using __get() and __set().

    Something similar can be accomplished when using __call(), i.e. you can detect when someone is calling getProperty() and setProperty() and handle accordingly.