php - 混合 __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';
触发,同时因为它正在分配一个值。它不仅抛出了我定义的自定义 trigger_error,而且也没有按预期填充数组。__get
invalidprop
__set
问题:如何在 __get() 中保留相同的附加功能的同时重现本机行为(带有 0 通知警告)?
解决方案
这样它工作正常:
<?php
class TestClass {
public function &__get($prop) {
echo "Get Prop: $prop\n";
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: $prop\n";
$this->$prop = $value;
}
}
$obj = new TestClass;
$obj->invalidprop = ['key' => 'test'];
var_dump($obj->invalidprop);
推荐阅读
- java - Primefaces 扩展 CK 编辑器始终呈现为 textarea
- jquery - 使用 Scrollmagic 同时启动两个动画
- android - 如何通过样式将自定义字体样式/系列应用于整个应用程序中的警报对话框
- php - 我应该在 Google Cloud Platform (PHP) 中使用什么数据库主机名
- python - Kivy:自定义鼠标光标在越过应用程序窗口的左边缘或上边缘时的不良行为
- javascript - 我可以在 Chrome 控制台中查看方法的来源吗?
- angular - 在模态/弹出窗口上,我想显示文本或 doc 文件
- python - 从 Google Apps 脚本运行本地 python 脚本
- ios - 如何快速比较两个字符串?
- java - 如何返回列表
对于列表