Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing private value in array, converted from object

Tags:

php

I have this little code:

class A
{
    private $val  = 5;
}

$a = new A();
$obj = (array)$a;
echo '<pre>'; var_dump ($obj); echo '</pre>';
echo $obj['Aval']; // error!

after dumping $obj, the result is:

array(1) {
  ["Aval"]=>
  int(5)
}

but accessing this value with $obj['Aval']; triggers an error - thats impossible!

like image 976
John Smith Avatar asked Mar 04 '26 17:03

John Smith


2 Answers

If you have a look at the documentation on converting to an array, it states:

private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.

This means that it's not A that's prepended, but \0A\0. So the key would be "\0A\0val".

Try the following code. It works.

class A {
    private $val  = 5;
}

$a = new A();
$obj = (array)$a;
echo '<pre>'; print_r ($obj); echo '</pre>';
echo $obj["\0A\0val"];

The error is because of the null bytes on either side.

like image 42
Mad Angle Avatar answered Mar 06 '26 07:03

Mad Angle