3

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?

Justin808
  • 20,859
  • 46
  • 160
  • 265
  • I don't think its quite a duplicate. I'm not concatenating things for one. I was thinking `$this->dataTitle` was a variable in and of it self; a class variable. With that thinking I didn't understand why it didn't work. – Justin808 May 16 '13 at 06:24
  • Nonetheless, it covers the correct syntax you should use for this concept. – Ja͢ck May 16 '13 at 06:25
  • Possibly, but just because two questions have the same answer does not mean they are the same question. Feel free to mark it for close, your choice. I just commented as to why I thought it wasn't a duplicate. – Justin808 May 16 '13 at 06:27
  • There are more answers than just the accepted one :) – Ja͢ck May 16 '13 at 06:40

2 Answers2

4

Try this:

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

Your expression is being parsed as:

$title = ($i->$this)->dataTitle;
Barmar
  • 741,623
  • 53
  • 500
  • 612
3

$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.

BlitZ
  • 12,038
  • 3
  • 49
  • 68
  • Bingo. Though why {} and not ()? I thought () was used to group things for order of operations, and that seems to be what is going on here? – Justin808 May 16 '13 at 06:02
  • @Justin808 It is not group order operation. It is property evaluation operation. – BlitZ May 16 '13 at 06:03