-1

Given the following class, why does get_object_vars return an empty array? This only happens when I'm extending PHP's ArrayObject but in the documentation I can't manage to find out the reason for this behavior.

class Test extends ArrayObject
{
    public $foo;
    public $bar;

    public function setFooBarValues( array $values )
    {
        $this->foo  = !empty( $values['foo'] ) ? $values['foo'] : null;
        $this->bar  = !empty( $values['bar'] ) ? $values['bar'] : null;
    }

    public function getArrayCopy()
    {
        return get_object_vars( $this );
    }
}

Running the following code that first sets the object's values shows that get_object_vars does not return the object's properties.

$object = new Test( array( 'lemon' => 1, 'orange' => 2, 'banana' => 3, 'apple' => 4 ) );
$object->setFooBarValues( array( 'foo' => 'x', 'bar' => 'y' ) );
var_dump( $object->getArrayCopy() );

Expected result:

array(2) {
  ["foo"]=>
  string(1) "x"
  ["bar"]=>
  string(1) "y"
}

Actual result:

array(0) {
}
halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61

1 Answers1

2

While the reason is not explained in the manual the object seems to handle all its properties internally. Take a look at the constructor's second parameter int $flags = 0 and the two flags provided in the manual:

  • ArrayObject::STD_PROP_LIST Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

  • ArrayObject::ARRAY_AS_PROPS Entries can be accessed as properties (read and write).

The constant STD_PROP_LIST is what you want to use for standard property access. Supplying the constructor with this constant will give you the result you are looking for:

$object = new Test(
    array( 'lemon' => 1, 'orange' => 2, 'banana' => 3, 'apple' => 4 ),
    ArrayObject::STD_PROP_LIST
);
$object->setValues( array( 'foo' => 'x', 'bar' => 'y' ) );
var_dump( $object->getArrayCopy() );

Result:

array(2) {
  ["foo"]=>
  string(1) "x"
  ["bar"]=>
  string(1) "y"
}
halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61