1

http://www.php.net/manual/en/functions.variable-functions.php#24931

That function does something like $this->{$this->varname}(). I tried it out and confirmed that that's valid syntax but it leaves me wondering... where does php.net discuss the use of curly brackets in variable names like that?

2 Answers2

1

Variable variables:

Class properties may also be accessed using variable property names. ...

Curly braces may also be used, to clearly delimit the property name.

See examples on that page, too.

Community
  • 1
  • 1
Wiseguy
  • 20,522
  • 8
  • 65
  • 81
  • 1
    Seems like {$this->varname}() ought to work then as well.. –  Apr 08 '13 at 21:46
  • `$s = (object)["varname" => "time"]; var_dump({$s->varname}());` this does not work. (results in parse error) – bwoebi Apr 08 '13 at 21:49
  • Why would you expect that to work? The braces aren't _within_ a variable expression there. – Wiseguy Apr 08 '13 at 21:58
  • Doesn't mean that disambiguation wouldn't be useful and that, it seems to me, is the main point of the {'s in the first place. http://stackoverflow.com/questions/15888945/class-variable-functions is an example of where it'd be useful. Call `{$this->varname}();` instead of `call_user_func('...')`. –  Apr 08 '13 at 22:02
  • Sure, I'm not arguing that it wouldn't be useful, just that it hasn't been designed to work that way. I'm guessing that the parser encounters a `{` that's not part of an unfinished expression and treats it like a regular block of code, like with `if () { ... }`. – Wiseguy Apr 08 '13 at 22:10
1

Why shouldn't it work?

These are variable variables/function names.

$f = "time";
$f(); // returns the actual time

It's now the same, only in object context (http://php.net/manual/en/functions.variable-functions.php):

$object->$f; // calls the method with the name $f in $object

Now, to say that it is the method with the name $this->varname, you need to write $this->{$this->varname} as $this->$this->varname will be interpreted as ($this->$this)->varname which results in $this->{$this->__toString()}->varname what you don't want.

bwoebi
  • 23,637
  • 5
  • 58
  • 79