This article does not repeat the object-oriented knowledge, this article focuses on the PHP constructor.
The constructor of a PHP class can be a magic cube __construct () or a function with the same name as the class, as in the following example:
classA{publicfunctionA(){echo'A is constructing...'; } classB{publicfunction__construct(){echo'B is contructing...'; $anew A(); // A is constructing...$bnew B(); // B is constructing...
In addition, when inheriting, it should be noted that:
" subclasses can not write constructors, then use the constructor of the parent class "
class A { protected $name ; Public function A () { echo ' A is constructing ...
' ; public function set_name ( $name ) { $this ->name = $name ; public function get_name () { return $this ->name; }} class B extends A { /* Public Function __ Construct () {echo ' B is contructing ...
'; } */} //$a = new A (); $b = new b (); //A is constructing ... $b ->set_name ( ' Zhangsan ' ); Echo $b ->get_name ();
" if the subclass writes a constructor, the constructor for the parent class is no longer called "
classA{protected$name; Public functionA(){Echo' A is constructing ...
'; } Public functionset_name($name){$this->name =$name; } Public functionget_name(){return$this->name; } } classBextendsA{ Public function__construct(){Echo' B is contructing ...
'; } }//$a = new A ();$b=NewB ();//Just echo ' B is contructing ... '$b->set_name (' Zhangsan ');Echo$b->get_name ();//Zhangsan
" if the constructor of the parent class is private, it can be inherited, but the subclass must have its own constructor and explicitly write "
classA{protected$name;Private functionA(){Echo' A is constructing ...
'; } Public functionset_name($name){$this->name =$name; } Public functionget_name(){return$this->name; } } classBextendsA{ Public function__construct(){Echo' B is contructing ...
'; } }//$a = new A ();$b=NewB ();//B is contructing ...$b->set_name (' Zhangsan ');Echo$b->get_name ();//Zhangsan
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The above describes the PHP object-oriented constructor description, including the aspects of the content, I hope the PHP tutorial interested in a friend helpful.