首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

PHP:如何将子类__construct()参数传递给parent :: __ construct()?

在 PHP 中,要将子类的 __construct() 方法的参数传递给父类的 __construct() 方法,可以使用 parent::__construct() 方法。以下是一个示例:

代码语言:php
复制
class ParentClass {
    public function __construct($arg1, $arg2) {
        echo "Parent constructor called with args: $arg1, $arg2";
    }
}

class ChildClass extends ParentClass {
    public function __construct($arg1, $arg2) {
        parent::__construct($arg1, $arg2);
    }
}

$child = new ChildClass("value1", "value2");

在这个示例中,我们有一个父类 ParentClass 和一个子类 ChildClass。子类的 __construct() 方法通过 parent::__construct() 调用父类的构造函数,并传递参数 $arg1$arg2

当我们创建一个 ChildClass 对象并传递两个参数时,父类的构造函数将被调用并接收这些参数。输出将是:

代码语言:txt
复制
Parent constructor called with args: value1, value2

这就是如何在 PHP 中将子类的 __construct() 方法参数传递给父类的 __construct() 方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券