gpt4 book ai didi

php - ArrayObject 迭代

转载 作者:可可西里 更新时间:2023-11-01 01:06:54 24 4
gpt4 key购买 nike

问题:

当手动设置或读取值时,ArrayObject 会按预期工作,但是当使用函数(例如 foreach)对其进行迭代时,事情会变得很糟糕。

它不调用我定义的 offset* 方法,而是使用 ArrayIterator 方法。

代码:

类:

class obsecureArray extends ArrayObject {


public function offsetSet($name, $value) {
call_user_func_array(array('parent', __FUNCTION__), array(base64_encode($name), base64_encode($value)) );
}

public function offsetGet($name) {
return base64_decode( call_user_func_array(array('parent', __FUNCTION__), (array) base64_encode($name) ) );
}

public function offsetExists($name) {
return call_user_func_array(array('parent', __FUNCTION__), (array) base64_encode($name) );
}

public function offsetUnset($name) {
return call_user_func_array(array('parent', __FUNCTION__), (array) base64_encode($name) );
}
}

使用示例:

$a = new obsecureArray();
$a['test'] = 'Value';
$a[2] = '1';

define('BR','<br />');
echo 'test: ',$a['test'],BR,'2: ',$a[2],BR;

foreach($a as $key => $value)
echo 'Key: ',$key,' Value:',$value,BR;

输出:

test: Value
2: 1
Key: dGVzdA== Value:VmFsdWU=
Key: Mg== Value:MQ==

CodePad example.

最佳答案

我查看 ArrayObject __construct方法 documentation并找到与我的问题相关的第三个参数:

iterator_class:

Specify the class that will be used for iteration of the ArrayObject object. ArrayIterator is the default class used.

现在我可以扩展 ArrayIterator使用我自己的 offset* 方法并将其传递给我的 ArrayObject 的构造函数,所以我查看了 ArrayIterator 并且它几乎与 ArrayObject 除了它显然没有使用外部迭代器。所以我所要做的就是改为扩展 ArrayIterator。并且还必须覆盖 currentkey 方法。

所以我有:

class obsecureArray extends ArrayIterator {

public function offsetSet($name, $value) {
call_user_func_array(array('parent', __FUNCTION__), array(base64_encode($name), base64_encode($value)));
}

public function offsetGet($name) {
return base64_decode(call_user_func_array(array('parent', __FUNCTION__), (array) base64_encode($name)));
}

public function offsetExists($name) {
return call_user_func_array(array('parent', __FUNCTION__), (array) base64_encode($name));
}

public function offsetUnset($name) {
return call_user_func_array(array('parent', __FUNCTION__), (array) base64_encode($name));
}

public function key() {
return base64_decode(parent::key());
}

public function current() {
return base64_decode(parent::current());
}



}

它按预期完美运行。

和为了:

$a = new obsecureArray();
$a['test'] = 'Value';
$a[2] = '1';

define('BR','<br />');
echo 'test: ',$a['test'],BR,'2: ',$a[2],BR;

foreach($a as $key => $value)
echo 'Key: ',$key,' Value:',$value,BR;

我得到了:

test: Value2: 1Key: test Value:ValueKey: 2 Value:1

CodePad example

关于php - ArrayObject 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8814269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com