我希望能够在父构造函数中设置私有属性的值,并在子构造函数或方法中调用该值。
例如:
<?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”是私人的,可以调用和显示...对吗? 在子类与父类中分配值是否存在问题?
希望能帮助您理解原因。
谢谢。
我希望能够在父构造函数中设置私有属性的值,并在子构造函数或方法中调用该值。例如:
protected
。但是,另一种方法是为您的父类实现get
方法,该方法允许您访问该属性,或者如果希望覆盖它,则可以实现set
方法。