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,
To call a function from a string stored in a variable, use $func.
Noun. curly-bracket language (plural curly-bracket languages) (programming) A programming language whose syntax uses curly brackets to enclose blocks, such as C, C++, Java, or C#.
You have to SHIFT key press for the double quotes and for the curly brackets. It would be quicker though if you strictly use double quotes.
In Java when you open a curly brace it means that you open a new scope (usually it's a nested scope). One important thing to understand is that a variable that you'll define inside this scope (which end where you put the closing curly brace) will not be recognized outside of the scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With