0

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;

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.