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?

4
  • 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. Commented May 16, 2013 at 6:24
  • Nonetheless, it covers the correct syntax you should use for this concept. Commented May 16, 2013 at 6: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. Commented May 16, 2013 at 6:27
  • There are more answers than just the accepted one :) Commented May 16, 2013 at 6:40

2 Answers 2

4

Try this:

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

Your expression is being parsed as:

$title = ($i->$this)->dataTitle;
Sign up to request clarification or add additional context in comments.

2 Comments

PHP Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in SimpleList.php
Fixed it. An expression after -> has to be in {}.
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.

2 Comments

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 It is not group order operation. It is property evaluation operation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.