1

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

Sam
  • 16,435
  • 6
  • 55
  • 89
Lukas
  • 9,752
  • 15
  • 76
  • 120
  • 5
    The key names begin with asterisks... So `$arr['body']` does not exist, it's `$arr['*body']`. – BenM Aug 14 '14 at 08:11
  • 3
    This looks an object that has been cast to an array, and those keys beginning with a * are protected properties (they don't actually begin with a *, the * is wrapped in null bytes... Use the library object, don't try to treat it as an array... the object provides a magic getter, so $myObject->body should have worked perfectly well if you hadn't cast it to an array – Mark Baker Aug 14 '14 at 08:24
  • Thank you @MarkBaker that was it. I serialized an object with private properties to the array and that was the cause of all the mess. – Lukas Aug 14 '14 at 09:42
  • If you can unserialize, with the class definition file loaded, then you should be able to restore your object.... that'll make it a lot easier to access the properties – Mark Baker Aug 14 '14 at 09:48

4 Answers4

3

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

gadz82
  • 92
  • 4
3

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.

Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
BenM
  • 52,573
  • 26
  • 113
  • 168
1

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.

Lukas
  • 9,752
  • 15
  • 76
  • 120
0

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)

paolo
  • 2,528
  • 3
  • 17
  • 25