PHP class declaration and instantiation, constructor and constructor, and php. PHP class declaration and instantiation and constructor are described in detail. php describes the declaration and instantiation of PHP classes, as well as the constructor and constructor methods. I would like to share with you the declaration and instantiation of PHP classes, detailed descriptions of constructor methods and constructor methods, and detailed descriptions of php classes.
This article describes the declaration and instantiation of PHP classes, as well as the constructor and Destructor. We will share this with you for your reference. The details are as follows:
<? Phpclass human {public static $ leg = 2; public $ name = 'Leo '; public $ age = '25'; public function cry () {}}$ leo = new human (); print_r ($ leo);/* returns the human Object ([name] => leo [age] => 25) * /// why is there no leg? // Because static is added, it becomes the attribute of the class. it is the permission modifier of the object that belongs to all // objects after the instance of this class is passed, permission modifiers include public, protected, and private // var is often used in PHP4, which is not recommended at present, it is equivalent to public // will resolve var to public in PHP5?>
Is there any way to change the attributes of an object by passing parameters when a new object is created? Not the same
A: You can define the constructor in the class, that is, the constructor will execute the object during initialization and can receive parameters.
As follows:
<? Php class human {public static $ leg = 2; public $ name = 'Leo '; public $ age = '25'; public function _ construct ($ name, $ age) {$ this-> name = $ name; $ this-> age = $ age ;}}$ leo = new human ('macro ', '23 '); print_r ($ leo);/* returns the human Object ([name] => macro [age] => 23). you can see that the parameter takes effect. _ construct is the constructor */?>
Corresponding to the constructor is the destructor, that is,
As follows:
<? Php class human {public static $ leg = 2; public $ name = 'Leo '; public $ age = '25'; public function _ construct ($ name, $ age) {$ this-> name = $ name; $ this-> age = $ age; echo $ this-> name. "The object is generated.
";} Public function _ destruct () {echo $ this-> name." The object is destroyed.
";}}$ Leo = new human ('macro ', '23'); $ tim = new human ('Tim', '18'); unset ($ leo ); echo '~~~~~~~~~~~~~~~~~~~~
';/* Returned: the macro object is generated. The tim object is generated. the macro object is destroyed ~~~~~~~~~~~~~~~~~~~~ The tim object is destroyed * // _ destruct is the destructor, that is, when the object is destroyed, it is called // why $ tim has executed the destructor even if there is no unset. // This is an implicit destruction, unset is explicitly destroyed. // when a page is automatically destroyed after execution?>