Array to Object and Object to Array in PHP – interesting behaviour

The array key contains a marker that this should be a private property of the class test.

Compare your scripts output with the following:

$array = array(
    "xpublic" => "x1", 
    # this will become a private member:
    "\x00test\x00xprivate" => "x2",
    # this will become a protected member:
    "\x00*\x00xprotected" => "x3"
);

var_dump($array);

$obj = (object) $array;

var_dump($obj);

When serialized, the same string is used to describe the private members.

Output:

array(3) {
  ["xpublic"]=>
  string(2) "x1"
  ["testxprivate"]=>
  string(2) "x2"
  ["*xprotected"]=>
  string(2) "x3"
}

object(stdClass)#1 (3) {
  ["xpublic"]=>
  string(2) "x1"
  ["xprivate":"test":private]=>
  string(2) "x2"
  ["xprotected":protected]=>
  string(2) "x3"
}

In the output of var_dump(), the null bytes are not visible.

(Update: Added protected class member)

Leave a Comment