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

2025-10-21 07:27:05

1、构造函数

void __construct ([ mixed $args [, $... ]] )

构造函数可以接受参数,能够在创建对象时赋值给对象属性

构造函数可以调用类方法或其他函数

构造函数可以调用其他类的构造函数

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

2、子类继承了父类,输出结果如下图所示

<?php

    header('Content-type:text/html;charset=utf-8');

    class Base    //父类

    {

        public function __construct()    //父类构造函数

        {

            echo "父类的构造函数"."<br>";

        }

    }

    class Child extends Base     //子类

    {

        public function __construct()    //子类构造函数

        {

            echo "子类的构造函数"."<br>";

        }       

    }

    $childClass = new Child();    //对类的实例化

?>

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

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

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

4、代码实例(执行结果如下图所示):

<?php

    header('Content-type:text/html;charset=utf-8');

    class Base    //父类

    {

        public function __construct()    //父类构造函数

        {

            echo "父类的构造函数"."<br>";

        }

    }

    class Child extends Base     //子类

    {

        public function __construct()    //子类构造函数

        {

            echo "子类的构造函数"."<br>";

            parent::__construct();    //调用父类构造函数

        }      }

    $childClass = new Child();    //对类的实例化

?>

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

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

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

6、代码实例(执行结果如下图所示):

<?php

    header('Content-type:text/html;charset=utf-8');

    class Base    //父类

    {

        public function __construct()    //父类构造函数

        {

            echo "父类的构造函数"."<br>";

        }

    }

    class Child extends Base     //子类 

    {

        public function __construct()    //子类构造函数

        {

            echo "子类的构造函数"."<br>";

            parent::__construct();    //调用父类构造函数

            Base::__construct();    //调用父类构造函数

        }            }

    $childClass = new Child();    //对类的实例化

?>

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

7、带参数的构造函数(执行结果如下图所示):

<?php

header('Content-type:text/html;charset=utf-8');

class Base{    // 声明类

    public $name; // 声明属性

    public $sex;

    public $age;

    function __construct($name,$sex,$age){

        $this -> 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");

?>

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢