简体   繁体   中英

PHP curly brace syntax for calling methods using string

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,

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM