How to use object of type ClassName as array [ 2.0 版本 ]
想請教
class model {
public $que ;
}
$model = new model();
$model['que'] = 'xxx'; // not working 型別不對
$model->que = 'abc';
但是 yii 的 $model = new $model();
$model['que'] = 'xxx'; // 卻可以 到底怎麼做到的!!
有人可以幫我解惑嗎~~ yii 他是怎麼處理的
最佳答案
-
The tricker is ArrayAccess.
class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayable {
You can try the following:
<?php class model implements ArrayAccess { public $que ; //This method is required by the SPL interface [[\ArrayAccess]]. public function offsetExists($offset) { return $this->$offset !== null; } //This method is required by the SPL interface [[\ArrayAccess]]. public function offsetGet($offset) { return $this->$offset; } //This method is required by the SPL interface [[\ArrayAccess]]. public function offsetSet($offset, $item) { $this->$offset = $item; } //This method is required by the SPL interface [[\ArrayAccess]]. public function offsetUnset($offset) { $this->$offset = null; } } $model = new model(); $model['que'] = 'xxx'; // <================ it works now%
共 1 条回复bryson 觉得很赞
其他 0 个回答
没有找到数据。
bryson Taipei
注册时间:2015-07-22
最后登录:2017-04-03
在线时长:84小时54分
最后登录:2017-04-03
在线时长:84小时54分
- 粉丝19
- 金钱4885
- 威望230
- 积分8025