【发布时间】:2011-07-24 09:01:21
【问题描述】:
我希望能够在父构造函数中设置私有属性的值,并在子构造函数或方法中调用该值。
例如:
<?php
abstract class MainClass
{
private $prop_1;
private $prop_2;
function __construct()
{
$this->prop_2 = 'this is the "prop_2" property';
}
}
class SubClass extends MainClass
{
function __construct()
{
parent::__construct();
$this->prop_1 = 'this is the "prop_1" property';
}
public function GetBothProperties()
{
return array($this->prop_1, $this->prop_2);
}
}
$subclass = new SubClass();
print_r($subclass->GetBothProperties());
?>
输出:
Array
(
[0] => this is the "prop_1" property
[1] =>
)
但是,如果我将prop_2 更改为protected,输出将是:
Array
(
[0] => this is the "prop_1" property
[1] => this is the "prop_2" property
)
我基本了解 OO 和 php,但我不知道是什么阻止了 prop_2 在 private 时被调用(或显示?);它不能是私人/公共/受保护的问题,因为“prop_1”是私人的,可以被调用和显示......对吗?
在子类与父类中分配值是否存在问题?
如果能帮助我理解原因,我将不胜感激。
谢谢。
【问题讨论】:
-
我在这里可能是错的,但是当您的子类的构造函数运行时,您的代码似乎正在创建一个名为 prop_1 的公共属性。这就是为什么你得到 prop_1 的输出而不是 prop_2 的输出。您应该能够通过在父类中实现 getter 和 setter 来解决这个问题。
-
感谢 ZeSimon,这就是我一直在寻找的东西(为什么我得到了 prop_1)。
-
那么回显出来的prop_1不是抽象类的prop_1吗?
标签: php inheritance properties private construct