I want to create dynamic object property as variable in php. For example
$b = '';
if($b != '') $b = "->b";
$a = new stdClass();
$a. $b->c;
My Target Output is
If(b == '') $a->c;
else $a->b->c;
For $b->c to work, you have to make $b an object of stdClass class. But since you made $b as a string using $b = "->b";, the former statement $b->c would throw error.
So the workaround is - make b as a property of object $a and assign an object of class stdClass to this member property. The following block of code would make this concept more clearer.
$b = '';
$a = new stdClass();
if($b != ''){
$a->b = new stdClass();
$a->b->c = 'something';
}else{
$a->c = 'something else';
}
Later, you can have the desired target output like this:
if($b == '') echo $a->c;
else echo $a->b->c;