I’m trying to save the state of the private property in a parent class when exporting and importing without allowing access to the property anywhere else. I’m storing the state by exporting to a file.
Take a class with private properties, export it with var_export()
and initialize it with __set_state()
too easy.
Now subclass it and try the same thing. You can’t set the private property of the parent class in __set_state()
. Can you?
Maybe I should be using serialize instead but is there a way to get this to work?
I tried:
priA3 = 'priA3';
}
public static function __set_state($an_array)
{
$obj = new A;
$obj->priA3 = $an_array['priA3'];
return $obj;
}
}
$a = new A;
$b = var_export($a, true);
eval('$c=" . $b . ";');
print_r($c);
echo $br;
class B extends A
{
public function __construct()
{
parent::__construct();
}
public static function __set_state($an_array)
{
$obj = new B;
// \|/ Creation of dynamic property B::$priA3 is deprecated
// $obj->priA3 = $an_array['priB3'];
// \|/ Cannot access private property A::$priA3
// parent::$priA3 = $an_array['priA3'];
return $obj;
}
}
$a = new B;
$b = var_export($a, true);
eval('$c=" . $b . ";');
print_r($c);
Workaround I found was to either use optional parameters in the constructor for initialization of the properties, use __set()
to access the overloaded property, or a protected method to set it. I don’t think these are good options.
The parent class would create the private property so adding an optional parameter in the constructor or allowing it to be set any other way would not work, it shouldn’t be visible to anything but the parent class.
Otherwise maybe i should be using serialize instead for this?