PHP的魔术方法捉array_push [英] php magic method to catch array_push
问题描述
我要寻找一种方式来拦截 array_push
< /一>,因为当这将是检索它的阵列的每个值具有像另一个信息:
I am looking for a way to intercept the action in array_push
, because when it will be retrieve it each value of the array has another info like:
class ClassName {
var $test = array();
function __set($attr, $value) {
$this->$attr = 'My extra value'.$value;
}
function index(){
array_push($this->test, "some val");
array_push($this->test, "some other val");
print_r($this->test);
}
}
$o = new ClassName();
$o->index();
和希望得到的东西,如:
And expected to get something like:
Array
(
[0] => My extra value some val
[1] => My extra value some other val
)
但我得到:
Array
(
[0] => some val
[1] => some other val
)
感谢所有
推荐答案
而不是使用数组,你可以使用实现了ArrayAccess接口的类。这样,你有超过你时追加到数组中发生的事情完全控制。
Instead of using an array, you can use a class that implements the ArrayAccess interface. This way you have full control over what occurs when you append to the array.
http://php.net/manual/en/class.arrayaccess.php
的缺点是,并非所有的阵列功能将对象(即排序等)上工作,但你可以把像这样:
The drawback is that not all array functions will work on the object (ie sorting etc), but you can push like so:
$object[] = 'new value';
另一种方法是简单地做一个包装函数添加到阵列中。
The alternative is to simply make a wrapper function for adding to the array.
public function addToArray($key, $value) {
if ($key === null) {
$this->test[] = 'My extra value ' . $value;
} else {
$this->test[$key] = 'My extra value ' . $value;
}
}
这篇关于PHP的魔术方法捉array_push的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!