php面向对象之构造函数

构造函数是类的特殊方法,实例化对象时,会自动调用
如果一个类中没有名为 __construct( )的方法,PHP将搜索一个php4中的写法,与类名相同名的构造方法
类只能声明一个构造方法,不能进行主动调用,用于在实例化对象时,为成员属性赋初值

<?php
class City{
    public $road; //属性
    public $tree;
    public $house;
    public function __construct($road,$tree,$house)
    {
        $this->road = $road;
        $this->tree = $tree;
        $this->house = $house;
    }

    public function assess(){
        echo "road is ".$this->road."<br>";
        echo "tree is ".$this->tree."<br>";
        echo "house is ".$this->house."<br>";
    }
}
$CD = new City('bad','good','excellent');
$CD->assess();
?>

注意: 不要写成$this->$road = $road;
子类中定义了构造函数,就不会再调用父类的构造函数,用parent::__construct()来调用父类构造函数

<?php
class Father{
    public function __construct()
    {
        echo 'father';
    }
}
class Son extends Father {
    public function __construct()
    {
        parent::__construct();
        echo 'son';
    }
}
class Daughter extends Father {
    public function __construct()
    {
        echo 'daughter';
    }

}
new Father(); //father
new Son(); //father son
new Daughter(); //daughter 被子类构造方法覆盖
?>

如果子类没有构造函数,会自动使用父类为public的构造函数
子类的构造函数可以和父类的构造函数有不同的参数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容