6

I saw in this SO answer that one can use a string inside curly braces to call a PHP class method so that

$player->SayHi();

Can be alternative written as:

$player->{'SayHi'}();

My questions are:

What is this syntax called in PHP? and what happens if a wrong string that does not correspond to a method is used?

Also, can I use this syntax to call non class methods?

I looked at the answers in the linked post, and there is only links to PHP callback syntax, which does not seem to cover the curly brace syntax.

Thanks,

2
  • If it doesn't correspond to a method, you get an error, just like you would if you used the normal syntax. Commented Nov 2, 2014 at 6:06
  • In PHP when you call an object, you can access the method of object just calling by brace. Commented Nov 2, 2014 at 6:08

2 Answers 2

10

It's part of variable functions. When using variable variables or variable functions, you can replace the variable with any expression that returns a string by wrapping on braces. So you can do:

$var = 'SayHi';
$player->$var();

or you can do it in one step with:

$player->{'SayHi'}();

The syntax with braces is shown in the documentation of variable variables. The example there is for a variable class property, but the same syntax is used for class methods.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Could you also explain the curly brace a little bit? (when a string literal is used).
Like I said, you use curly braces when the value is an expression, not a variable. So you could do ->{$a.$b} if you wanted to concatenate variables.
I see. Thanks for the explanation. Is there any PHP reference for using curly braces to bracket expressions in this case? Sorry for the newbie question. I just haven't seen this before.
1

You can read about this in the PHP manual

Basicly:

function getVarName() 
{ return 'aMemberVar'; } 

print $foo->{getVarName()}; // prints "aMemberVar Member Variable"

Its a part of variable functions.

Comments

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.