The declaration of the PHP constructor is the same as the declaration of the other operation, except that its name must be __construct (). This is a change in PHP5, in the previous version, the name of the constructor must be the same as the class name, which can still be used in PHP5, but is now used by very few people, the advantage is that the constructor is independent of the class name, when the class name changes, you do not need to change the corresponding constructor name. To be backwards compatible, if a class does not have a method named __construct (), PHP will search for a constructor in PHP4 that has the same name as the class name. Format: function __construct ([parameter]) {...} Only one construction method can be declared in a class, but a constructor is called every time the object is created, and the method cannot be invoked actively, so it is often used to perform some useful initialization tasks. For example, an attribute is assigned an initial value when creating an object. 1.//Create a human 2. 3.0class Person 4. 0{5.//The following is the person's member attribute 6. var $name;//person's name 7. var $sex;//Human Gender 8. Var $age;//person's age 9.//Define a constructor method parameter for name $name, gender $sex and age $age. f Unction __construct ($name, $sex, $age) 11. {12.//$name to the Member attribute $this->name by means of the constructor method. $this->name= $name; 14.//$sex to the member property $this->sex the value 15 by means of the constructor method passed in. $this->sex= $sex; 16.//$age to the member property $this->age the value 17 by means of the constructor method passed in. $this->age= $age; 18.} 19. This man's way of speaking 20. function say () 21. {. echo "My name is called:". $this->name. "Gender:". $this->sex. "My Age is:". $this->age. "
"; 23.} 24. } 25. Create 3 Objects $p1, P2, $p 3 by constructing a method, passing in three different arguments for name, gender, and age 26, respectively. $p 1=new person ("Zhang San", "male", 20); $p 2=new person ("John Doe", "female", 30); $p 3=new person ("Harry", "male", 40); 29.//below access the $p1 object in the speech method 30. $p 1->say (); 31.//below access the $p2 object in the speech method 32. $p 2->say (); 33.//below access the $p3 object in the speech method 34. $p 3->say (); The output is: My name is called: Zhang San Sex: Male my age is: 20 my name is called: John Doe Sex: Female my age is: 30 My name is called: Harry Sex: Male My age is: 40
http://www.bkjia.com/PHPjc/767257.html www.bkjia.com true http://www.bkjia.com/PHPjc/767257.html techarticle The declaration of the PHP constructor is the same as the declaration of the other operation, except that its name must be __construct (). This is a change in PHP5, in the previous version, the constructor name must be the same as the class name, which ...