多语言展示
当前在线:1794今日阅读:165今日分享:48

子类如何引用父类的构造方法

下面小编给大家介绍两种子类引用父类的构造方法
工具/原料
1

php

2

sublime

方法/步骤
1

构造函数void __construct ([ mixed $args [, $... ]] )构造函数可以接受参数,能够在创建对象时赋值给对象属性构造函数可以调用类方法或其他函数构造函数可以调用其他类的构造函数

2

子类继承了父类,输出结果如下图所示';        }    }    class Child extends Base     //子类     {        public function __construct()    //子类构造函数        {            echo '子类的构造函数'.'
';        }            }    $childClass = new Child();    //对类的实例化?>

3

第一种引用方法:parent::__construct();

4

代码实例(执行结果如下图所示):';        }    }    class Child extends Base     //子类     {        public function __construct()    //子类构造函数        {            echo '子类的构造函数'.'
';            parent::__construct();    //调用父类构造函数        }      }    $childClass = new Child();    //对类的实例化?>

5

第二种引用方法:Base::__construct();(Base为父类名称)

7

带参数的构造函数(执行结果如下图所示): name = $name;    // 给属性name赋传进来的值        $this -> sex= $sex;        $this -> age = $age;    }}class Information extends Base {    function __construct($name,$sex,$age){        parent::__construct($name,$sex,$age);        echo $this -> name= $name;    }}new Information('小明','男','16');?>

注意事项

要执行父类的构造函数,需要在子类的构造函数中调用

推荐信息