php - 如何在使用某个键访问 ArrayObject 之前执行/触发方法
问题描述
我有一个 php ArrayObject
class myObject extends ArrayObject
{
public function __construct()
parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
// populate
$this->populateArray();
{
private function populateArray() {
$this['hello'] = null;
$this['hello2'] = null;
$this['hello3'] = null;
}
}
现在当我以这种方式访问 hello 元素时
$myArray = new myObject();
$value = $myArray['hello'];
我想触发 myObject 中的一个方法,该方法在读取之前将另一个对象分配给 $myArray。我的方法应该是这样的。
private function method($value) {
$this[$value] = new class2();
}
有没有办法做到这一点?
解决方案
您可以像这样覆盖offsetGet
函数:
public function offsetGet($index) {
$this->someMethod();
return parent::offsetGet($index);
}
private function someMethod()
{
echo "triggered";
}
然后当你跑
$x = new myObject;
echo $x['hello'];
将输出
触发
在someMethod()
你可以做任何你想做的事。
推荐阅读
- android - 在 x 轴上滑动时锁定水平 RecyclerView 中的 Y 轴滚动
- javascript - 如何在赛普拉斯(vscode)中进行自定义命令实现
- angular - 解析 mailto.api 期间的 HTTP 失败
- php - Elementor Widget 无法找到我的班级,返回致命错误
- java - 为什么 swing gui 的行为很奇怪?
- amazon-web-services - Glue 无法读取 S3 存储桶
- angular - 具有推断条件类型的 Angular 组件模型
- google-apps-script - 如何在谷歌表格的下拉列表中选择相同的项目时更新时间戳?
- python - 如何在类中在 python 中编写基于字符串的动态函数调度?
- microsoft-graph-api - Microsoft Teams 中私人频道的成员资格是否可以得到 AAD 组的支持?