0

I know accessing object's properties dynamically using string e.g.

$obj->{$string};

But what about objects themselves?

Like I have string

$obj = '$model->property';

How to use this?

For example in if statement, to have something like

if($model->property) but by using this string?

Tried if({$obj}), if(${$obj})... nothing works.

I don't know if it even possible, but maybe?

7
  • You could use eval I guess but it's unsafe... Commented May 5, 2018 at 11:14
  • @ka_lin tried eval, doesn't work, with eval I've got "Parse error: syntax error, unexpected end of file" Commented May 5, 2018 at 11:16
  • @ka_lin okay, my bad. added ";" now no exception. But {{ dd(eval('$model->id;')) }} gives me null hmmm. Idk, gives me only null all time Commented May 5, 2018 at 11:19
  • @ka_lin strange, but {{ dd($model->id) }} returns me 77 and {{ dd(eval('$model->id;')) }} null Commented May 5, 2018 at 11:37
  • Don't do this. What you are attempting is a bad practice, which will only lead to pain and misery. Besides, you are braking object's encapsulation Commented May 5, 2018 at 13:32

1 Answer 1

1

I've set up a small test case...

class A {
    public $b = 5;
}

$test = new A();
$var = "test";
echo ${$var}->b;

I think this last line is what your after.

Update:

If you want the object and the property, then the nearest I could get is to use...

class A {
    public $b = 5;
}

$test = new A();
$var = "test->b";
list($var, $property) = explode("->", $var);
echo ${$var}->$property;
Sign up to request clarification or add additional context in comments.

11 Comments

But I need object + property in one string, as string and as one
Can't it be done easier like e.g. ${$var}; ? where $var = "test->b"; (without usting list and explode)
Not as far as I know - maybe someone else can come up with a way of doing it. BUT I would avoid using eval().
@krystian2160 This is the easiest way. You could also loop trough what the array explode returns if you want a variable amount of properties.
@Joas I know Joas, thank you :D. I just wonder why there is no other (easier, simpler) way
|

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.