PHP doesn't find array elements

165 views Asked by At

A library I use uses an array. Applying print_r to that array prints this:

Array
(
    [*queueId] => 1
    [*handle] => 9b875867b36d568483fb35fdb8b0bbf6
    [*body] => First string in the TestQueue
    [*md5] => c23ba714199666efbc1dcd5659bb0a0a
    [*timeout] => 1408003330.6534
    [*id] => 2
    [*creationdate] => 2014-08-13 16:03:37
)

The library uses a magic getter on that array

public function __get($key)
{
    if (!array_key_exists($key, $this->_data)) {
        throw new Exception\InvalidArgumentException("Specified field \"$key\" is not in the message");
    }
    return $this->_data[$key];
}

When I try to access

$myObject->body

I run into the exception. In fact, the debugger shows that array_key_exists will return false while the _data array is available as printed above

4

There are 4 answers

0
gadz82 On

The asterisk indicates that this array is a representation of an object, probably the original object property is protected. http://php.net/manual/en/language.types.array.php#language.types.array.casting

0
BenM On

As I explained in the comments, the array keys actually start with an asterisk. Since you can't call them using the regular syntax of $obj->*body (it'll cause a syntax error), you can use the following:

$myObject->{'*body'}

This should solve your problem.

0
paolo On

Assuming that $myObject is the array you are talking from:

You can't access arrays with ->, use $myObject['*body'] instead. (And you should as well change the name to $myArray, for example)

0
Lukas On

As @MarkBaker stated in the comment of my question, the problem was that I was serializing an object with private properties to the array. The asterisk were marks that these properties were private.