سؤال

I have a class, that actually operates over a complicated array to make the manipulation more simple. The format of original array looks like this:

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

The class takes array like above as constructor:

class NBT_traverser implements ArrayAccess {
    function __construct(&$array) {
       $this->array = $array;
    }
}

Then, this is how the members are accessed:

$parser = new NBT_traverser($somearray);   
echo $parser["foo"];  //"somevalue"   

When I print_R the class, I get the list of its values and the original complicated array. Like this:

 object(NBT_traverser)#2 (1) { 
    ["nbt":"NBT_traverser":private]=> &array(1) {
 /*Tons of ugly array contents*/
 }

Instead, I'd like to get this like the output of print_r:

array(
    "foo" => "somevalue"
)

Is it possible to trick the print_r to do this? Current behavior makes it harder to debug with the class, than without it.
Of course, I can write my own method to print it, but I want to make the usage more simple for the users of the class. Instead, I wanted to give print_R something, that It will print as array.

هل كانت مفيدة؟

المحلول

You should not have issues if you are extending ArrayAccess just write a method to get your values

Example

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

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

Output

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

Class Used

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;
    }
}

نصائح أخرى

You could use the __toString function in your class

class Test
{
    private $_array = array();

    public function __toString()
    {
        return print_r($this->_array, true);
    }
}

And then just echo out your class

$test = new Test();
echo $test;

I think this would print out your array as you want it to be?

Array
(
)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top