本文不再赘述html' target='_blank'>面向对象的知识,本文着重说明PHP的构造函数。
php类的构造函数可以是魔术魔方__construct() 也可以是和类同名的函数,实例如下:
class A{ public function A(){ echo 'A is constructing...'; } } class B{ public function __construct(){ echo 'B is contructing...'; } } $a = new A(); // A is constructing... $b = new B(); // B is constructing...
此外,在继承时,应该注意的是:
【子类可以不写构造函数,那么使用父类的构造函数】
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 = new B(); // A is constructing... $b->set_name('zhangsan'); echo $b->get_name();
【子类如果写了构造函数,那么不会再调用父类的构造函数了】
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 = new B(); // just echo 'B is contructing...' $b->set_name('zhangsan'); echo $b->get_name(); // zhangsan
【父类的构造函数如果是私有的,可以被继承,但是子类必须有自己的构造函数,并且明确写出来】
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 = new B(); // B is contructing... $b->set_name('zhangsan'); echo $b->get_name(); // zhangsan
PHP编程 郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
新闻热点
疑难解答