PHP5 is introducing the Object Oriented Programmation foundments. This include the creation of some methods used to help the manipulation of objects. They can make automated tasks (usually boring), catch lost calls to unexisting methods or preperties…
In an Architect side, I would say that the usage of theses methods is the inverse of a best pratice, but in some specifics jobs, they could really help.
“Magic methods” List for PHP5:
- __construct()
- __destruct()
- __set()
- __get()
- __call()
- __toString()
- __sleep()
- __wakeup()
- __isset()
- __unset()
- __autoload()
- __clone()
__construct()
Method called during object building.
__destruct()
Method called during object destruction.
__set()
Method called while trying to assign a value to a non-existing property.
__get()
Method called while trying to read a non-existing property.
__call()
Method called while trying to calla non-existing method.
__toString()
Method called when someone tries to transform an object to string (using echo or print)…
__sleep()
Method used to serialyze objects in PHP5. It has to define to correct way to serialyze.
__wakeup()
De-serialyze method. It has to define the de-serialyzing way of the object.
__isset()
This method helps to check the existence of a method.
__unset()
Method used for object destruction.
__autoload()
This method is called while trying to load an object from a separated file without having it already loaded with “include”, “require” or “require once”.
__clone()
This method define the way to clone the object..
Example :
<?php class MyClass { public $Name; public function __set($var, $val) { echo ("The property : ".$var." - Value : ".$val); } } $systemvars = new MyClass(); $systemvars->adminEmail = 'toto@toto.fr'; ?>
This will output
The property : adminEmail - Value: toto@toto.fr
This is not a best practice !
In fact, despite some very few cases, this methods shouldn’t be used to define beans. The only correct way is to create a file containing the “hardcoded” bean definition.
Best Practice is :
<?php class MyClass { private $adminEmail; public function setAdminEmail ($var) { $this->adminEmail = $var; } public function getAdminEmail() { return $this->adminEmail; } } $systemvars = new MyClass(); $systemvars->setAdminEmail ('toto@toto.fr'); ?>
It is really important for code stability to respect best practices, but sometimes, flexibility is need… This is what I try to explain in this article.





Community Area - You can add comments here