混合__get和__set调用的PHP问题



混合使用__get和__set方法时遇到问题

class TestClass {}
$obj = new TestClass();
var_dump($obj->test); //throw notice as expected
$obj->invalidprop['key'] = 'test';
var_dump($obj->invalidprop);
//=> array('key' => 'test')

通过用一个值为的数组填充动态属性,本机行为可以完美地工作,而不需要任何警告/通知。

但是,一旦我添加了__get和__set来添加一些功能,我就无法再现默认行为。

class TestClass {
public function &__get($prop) {
if (method_exists($this, 'get' . $prop)) {
$func = 'get' . $prop;
return $this->$func();
}
//else throw default notice warning
trigger_error('Undefined property ... ');
}
public function __set($prop, $value) {
$this->$prop = $value;
}
}

所以我再次运行$obj->invalidprop['key'] = 'test';,它在访问invalidprop时触发__get,同时触发__set,因为它正在赋值。它不仅抛出我定义的自定义trigger_error,而且没有按预期填充数组。

问题:如何在__get((中保留相同的附加功能的同时再现本机行为(0注意警告(?

这样就可以很好地工作:

<?php
class TestClass {
public function &__get($prop) {
echo "Get Prop: $propn";
if (method_exists($this, 'get' . $prop)) {
$func = 'get' . $prop;
return $this->$func();
}
//else throw default notice warning
trigger_error('Undefined property ... ');
}
public function __set($prop, $value) {
echo "Set Prop: $propn";
$this->$prop = $value;
}
}
$obj = new TestClass;
$obj->invalidprop = ['key' => 'test'];
var_dump($obj->invalidprop);

只能将变量作为ref传递,不能传递函数结果。在CCD_ 5中;设置"-仅";得到";并通过引用修改值。

示例

<?php
class TestClass {
private $props = [];
public function &__get($a) {
if (!array_key_exists($a, $this->props)) {
$this->props[$a] = [];
}
$a = &$this->props[$a];
return $a;
}
}
$obj = new TestClass();
$obj->invalidprop['key'] = 'test';
var_dump($obj->invalidprop);

结果:

array(1) {
["key"]=>
string(4) "test"
}

最新更新