Since the release of Php5.0, many object-oriented features have been provided for us, especially a lot of easy-to-use magic methods. These magic methods allow us to simplify our coding, better design our system. Today, let's get to know the magic methods provided by php5.0.
1. _ construct () when instantiating an object, this method of this object is called first.
class Test { function __construct() { echo "before"; } } $t = new Test(); |
The output is:
Start
We know that the php5 object model and the function with the same class name are class constructor. If we define the constructor and the _ construct () method at the same time, php5 calls the constructor by default instead of the _ construct () function. Therefore, _ construct () is the default constructor of the class.
2. _ destruct () This method is called when an object or object operation is terminated.
Class Test {function _ destruct () {echo "end" ;}}$ t = new Test (); the end |
We can release resources at the end of the object operation.
3. _ get () is called when an attempt is made to read an attribute that does not exist.
If you try to read an attribute that does not exist in an object, PHP will give an error message. If the _ get method is added to the class, and we can use this function to implement operations similar to reflection in java.
Class Test {public function _ get ($ key) {echo $ key. "does not exist" ;}}$ t = new Test (); echo $ t-> name; the output is: name does not exist |
4. _ set () is called when you try to write a value to an attribute that does not exist.
Class Test {public function _ set ($ key, $ value) {echo ''. $ key. "value ". $ value ;}}$ t = new Test (); $ t-> name = "aninggo"; the output is aninggo. |
5. _ call () This method is called when an object does not exist.
Class Test {public function _ call ($ Key, $ Args) {echo "The {$ Key} method you want to call does not exist. The parameter you passed in is: ". print_r ($ Args, true) ;}}$ t = new Test (); $ t-> getName (aning, go ); |
The program will output:
The getName method you want to call does not exist. The parameter is Array.
(
[0] => aning
[1] => go
)
6. _ toString () is called when an object is printed.
This method is similar to the toString method of java. We call this function when we print the object directly.
Class Test {public function _ toString () {return "Print Test" ;}}$ t = new Test (); echo $ t; |
When echo $ t; is run, $ t->__ toString () is called to output
Print Test
7. _ clone () is called when the object is cloned.
Class Test {public function _ clone () {echo "I have been copied! ";}}$ T = new Test (); $ t1 = clone $ t; program output: I have been cloned! |
1