Accessing a private value in an array, converted from an object

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 resetting $ obj, the result is:

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

      

but accessing this value with $ obj ['Aval']; raises an error - it's impossible!

+3


source to share


3 answers


If you look at the documentation when converting to an array , it says:

private variables have a class name appended to the variable name; protected variables have "*" appended to the variable name. These preliminary values ​​have zero bytes on either side.



This means that it is not A

what is added, but \0A\0

. So the key will be "\0A\0val"

.

+8


source


Try the following code. He 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 has to do with null bytes on both sides.

+2


source


This code is tested:

class a
{
  private $x = "something";
}

$w = new a();

print_r($w); // object

print_r((array)$w); // cast as array

      

And this is the result:

a Object ( [x:a:private] => something ) Array ( [ax] => something ) // the print_r result

      

So what literally happened is that the class name (string) is appended to the variable name, making it x

equal ax

.

Although, as already said, to access a property, you must:

$arrayed = (array)$w;

var_dump($arrayed["\0a\0x"]);

      

Adding \0

before and after the class name and appending the concatenated string to the name of the key you want to access.

+1


source







All Articles