我正在使用反射來調整對象中的各種值,並且我有一個對象是我需要調整的父對象。如何從PHP的外部對象本身獲取父對象?
例如:
class Ford extends Car
{
private $model;
}
class Car
{
private $color;
}
我可以很容易地使用反射來改變模型,但如何從孩子分開父母,讓我可以在父使用反射?
什麼我希望一些僞代碼是可能的:
$ford = new Ford();
$manipulator = new Manipulator($ford);
$manipulator->set('model','F-150');
$manipulator->setParentValue('color','red');
class Manipulator
{
public function __construct($class) {
$this->class = $class;
$this->reflection = new \ReflectionClass($class);
}
public function set($property,$value) {
$property = $this->reflection->getProperty($property);
$property->setAccessible(true);
$property->setValue($this->class,$value);
}
public function setParentValue() {
$parent = $this->reflection->getParent();
$property = $this->reflection->getProperty($property);
$property->setAccessible(true);
// HOW DO I DO THIS?
$property->setValue($this->class::parent,$value);
}
}
問題的要點是:
在這種情況下,我怎麼可以改變顏色$從外部對象?
是否有類似Ford :: parent()或get_parent_object($ ford)的東西?
注意
上面使用的對象是沒有確切的方案,但只是用來說明該概念。在現實世界的情況下,我有一個父母/孩子的關係,我需要能夠從外部訪問/更改每個值。
ANSWER
請檢查我的回答如下......我想通了。
車應該有$模型屬性..它只是可以因爲它是私密的,所以不能訪問它。如果您在Car上使用反射並嘗試獲取$ model屬性,它是否會給您一個錯誤? – 2012-03-28 18:24:29
我還沒試過。我會嘗試,但在這種情況下,這幾乎是無關緊要的,我想。上面使用的對象並不是確切的場景,只是用來說明這個概念。在現實世界的情況下,我有一個父母/孩子的關係,我需要能夠從外部訪問/更改每個值。 – johnnietheblack 2012-03-28 18:29:09
PHP中的屬性沒有這種關係。你可以使用'parent :: myMethod()'來訪問父方法,但是你沒有看到屬性,因爲它們全都存在於同一個平面上..只有它們的範圍和可訪問性發生了變化。我可能完全錯誤地解釋了這個問題。如果你在Car/Ford例子中加入了(psuedo)反射代碼,它可能會有所幫助 – 2012-03-28 18:32:31