Php 如何在子类构造方法中获取父类变量值
我有两个文件: ParentClass.phpPhp 如何在子类构造方法中获取父类变量值,php,oop,parent-child,Php,Oop,Parent Child,我有两个文件: ParentClass.php <?php class ParentClass { public $variable1; public $variable2 = "Value of variable 2"; public function __construct() { $this->variable1 = "Value of variable 1"; } } $obj = new ParentClass
<?php
class ParentClass {
public $variable1;
public $variable2 = "Value of variable 2";
public function __construct()
{
$this->variable1 = "Value of variable 1";
}
}
$obj = new ParentClass;
?>
和ChildClass.php
<?php
include "ParentClass.php";
class ChildClass extends ParentClass {
public function __construct()
{
echo $this->variable1;
echo $this->variable2;
}
}
$obj = new ChildClass;
?>
当我在浏览器中运行ChildClass文件时,它只给出变量2的值。它不显示variable1的值。我需要打印variable1和variable2值。请提供帮助。您需要在子构造函数中调用parent::\u construct() 工作代码应为: ParentClass.php
<?php
class ParentClass {
public $variable1;
public $variable2 = "Value of variable 2";
public function __construct()
{
$this->variable1 = "Value of variable 1";
}
}
$obj = new ParentClass;
?>
和ChildClass.php
<?php
include "ParentClass.php";
class ChildClass extends ParentClass {
public function __construct()
{
echo $this->variable1;
echo $this->variable2;
}
}
$obj = new ChildClass;
?>
试试看它是否有效:)您需要从ChildClass::u construct()方法调用父构造函数:
parent::u construct()
是,当您实例化子类时,父类构造函数没有被调用,您必须在子类构造函数中调用它。我已经启动了ParentClass对象,因此当您执行时,构造函数将自动执行,而无需在子类中再次调用它它从父级重写了$obj
。不,我想在构造函数内部而不是外部为变量赋值。@AjmalRazeel您需要调用ChildClass::\uu构造()方法:父级::\uu构造();