Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP object property from class variable? [duplicate]

Tags:

php

Why does this work

foreach ($items as $i) {
    $dataTitle = $this->dataTitle;
    $title = $i->$dataTitle;
}

when this doesn't?

foreach ($items as $i) {
    $title = $i->$this->dataTitle;
}

Is there a better way to do this?

like image 958
Justin808 Avatar asked Sep 21 '26 23:09

Justin808


2 Answers

Try this:

$title = $i->{$this->dataTitle};

Your expression is being parsed as:

$title = ($i->$this)->dataTitle;
like image 101
Barmar Avatar answered Sep 23 '26 13:09

Barmar


$this referes to current object parsed in not obvious order. You need to use {expr} notation, to dynamicly evaluate property name.

Try to use {} around $this->dataTitle:

$title = $i->{$this->dataTitle};

Look at bottom part of last example in variable variables section of manual.

like image 20
BlitZ Avatar answered Sep 23 '26 11:09

BlitZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!