"foo", "type"-6ren">
gpt4 book ai didi

php - 类的 Print_R 作为数组

转载 作者:行者123 更新时间:2023-12-04 05:04:30 25 4
gpt4 key购买 nike

我有一个类,它实际上对一个复杂的数组进行操作,以使操作更简单。原始数组的格式如下所示:

array(
array(
"name" =>"foo",
"type" =>8, //The array is NBT format and 8 stands for string
"value" =>"somevalue"
)
}

该类将上述数组作为构造函数:
class NBT_traverser implements ArrayAccess {
function __construct(&$array) {
$this->array = $array;
}
}

然后,这是访问成员的方式:
$parser = new NBT_traverser($somearray);   
echo $parser["foo"]; //"somevalue"

当我 print_R类,我得到它的值列表和原始的复杂数组。像这样:
 object(NBT_traverser)#2 (1) { 
["nbt":"NBT_traverser":private]=> &array(1) {
/*Tons of ugly array contents*/
}

相反,我想得到这样的输出 print_r :
array(
"foo" => "somevalue"
)

是否有可能欺骗 print_r这样做?当前的行为使得使用类进行调试比不使用类更难。
当然,我 可以 编写我自己的方法来打印它,但我想让类的用户使用更简单。相反,我想给 print_R一些东西,它将打印为数组。

最佳答案

如果您要扩展 ArrayAccess,您应该不会遇到问题只需编写一个方法来获取您的值

例子

$random = range("A", "F");
$array = array_combine($random, $random);

$parser = new NBT_traverser($array);
echo $parser->getPrint();

输出
Array
(
[A] => A
[B] => B
[C] => C
[D] => D
[E] => E
[F] => F
)

使用的类
class NBT_traverser implements ArrayAccess {
private $used; // you don't want this
protected $ugly = array(); // you don't want this
public $error = 0202; // you don't want this
private $array = array(); // you want this
function __construct(&$array) {
$this->array = $array;
}

function getPrint() {
return print_r($this->array, true);
}

public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->array[] = $value;
} else {
$this->array[$offset] = $value;
}
}

public function offsetExists($offset) {
return isset($this->array[$offset]);
}

public function offsetUnset($offset) {
unset($this->array[$offset]);
}

public function offsetGet($offset) {
return isset($this->array[$offset]) ? $this->array[$offset] : null;
}
}

关于php - 类的 Print_R 作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15711080/

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