While reading PHP documentation, especially the OOP chapter, I’ve discovered a few functions I didn’t know of, even if I use a lot PHP in my daily job.
Please note that PHP5 was introduced in 2004, and these methods may evolve.
When calling a class (or an interface) still not declared, PHP will call the __autoload function, if it was declared sooner.
It can be usefull to reduce the number of require/include calls and parsing PHP files only on demand.
__construct / __destruct
Like other OOP languages, PHP provides generic constructors/destructors that will be called on object instantiation and destruction.
Note that destructor will be called even if object is not explicitaly destroyed (example: at the end of a script).
Visibility of private methods
PHP also manages private methods and variables. They are only accessible in their own instanciated object. But PHP allows to call a private method from an object instance from another object, as long as this object is from the same type. This is fully described in the OOP Visibility.
And this works:
The __toString function is a simple function allowing to define the class interacts when a String conversion of it is required (by using “print”).
In the same fashion, it is possible to define how the object will interact when being called as a function. This is done with the __invoke function
And when executing:
__get, __set, __isset, __unset
PHP allows affectation on any class instance any kind of values (like a hash table), as long as this is not a private variable:
When affecting a variable this way, PHP will call the __set/__get functions. And because of this, it is possible, with reimplementing those functions, to define a new behavior:
This example will return:
This also allows to protect the class contents. Note that if __set/__get is redefined, there won’t be anymore errors when trying to access private variables.
Those two functions, with the help of variable setters/getters, allow to entirely wrapper classes’ instances, allowing uses more interesting that simple inheritance.
__clone is called when asking for a copy of an object instance. This will result in 2 totally independant instances with the same content. While I’m not sure that clone is commonly used, __clone may be used to modify an object after cloning, or to not effectively clone the object ot use a singleton.