PHPUsage analysis of constructor
The declaration of the PHP constructor is the same as the declaration of other operations, except that its name must be construct(). This is a change in PHP5. In previous versions, the name of the constructor must be the same as the class name. This can still be used in PHP5, but now few people use it. The advantage of this is that the constructor can be Independent of the class name, there is no need to change the corresponding constructor name when the class name changes. For backward compatibility, if there is no method named construct() in a class, PHP will search for a constructor method written in php4 with the same name as the class name. Format: function construct ([parameter]) { … … } Only one constructor can be declared in a class, but the constructor will only be called once every time creates an object, and cannot be done proactively This method is called, so it is usually used to perform some useful initialization tasks. For example, assign an initial value to the attribute when creating the object.
1. //创建一个人类 2. 3. 0class Person 4. 0{ 5. //下面是人的成员属性 6. var $name; //人的名子 7. var $sex; //人的性别 8. var $age; //人的年龄 9. //定义一个构造方法参数为姓名$name、性别$sex和年龄$age 10. function construct($name, $sex, $age) 11. { 12. //通过构造方法传进来的$name给成员属性$this->name赋初使值 13. $this->name=$name; 14. //通过构造方法传进来的$sex给成员属性$this->sex赋初使值 15. $this->sex=$sex; 16. //通过构造方法传进来的$age给成员属性$this->age赋初使值 17. $this->age=$age; 18. } 19. //这个人的说话方法 20. function say() 21. { 22. echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."<br>"; 23. } 24. } 25. //通过构造方法创建3个对象$p1、p2、$p3,分别传入三个不同的实参为姓名、性别和年龄 26. $p1=new Person("张三","男", 20); 27. $p2=new Person("李四","女", 30); 28. $p3=new Person("王五","男", 40); 29. //下面访问$p1对象中的说话方法 30. $p1->say(); 31. //下面访问$p2对象中的说话方法 32. $p2->say(); 33. //下面访问$p3对象中的说话方法 34. $p3->say();
The output result is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40
The above is the detailed content of Detailed explanation on the use of constructors in php. For more information, please follow other related articles on the PHP Chinese website!