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:
class A{ Public function A(){ Echo ' A is constructing ... '; } } class B{ Public function __construct(){ Echo ' B is contructing ... '; } }$a=NewA ();//A is constructing ... $b=NewB ();//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...<br> '; } 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...<br> '; } */}//$a = new A (); $b=NewB ();//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 "
class A{ protected $name; Public function A(){ Echo ' A is constructing...<br> '; } 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...<br> '; } }//$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 "
class A{ protected $name;Private function A(){ Echo ' A is constructing...<br> '; } 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...<br> '; } }//$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.
PHP Object-oriented constructor description