码迷,mamicode.com
首页 > Web开发 > 详细

PHP面向对象构造函数说明

时间:2015-08-30 15:58:14      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:php   构造函数   面向对象   

本文不再赘述面向对象的知识,本文着重说明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面向对象构造函数说明

标签:php   构造函数   面向对象   

原文地址:http://blog.csdn.net/zhaozonglu/article/details/48104645

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!