Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP curly brace syntax for calling methods using string

Tags:

syntax

php

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,

like image 448
thor Avatar asked Nov 02 '14 06:11

thor


People also ask

How do you call a function from a string in PHP?

To call a function from a string stored in a variable, use $func.

What is curly bracket syntax?

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#.

How Print curly braces PHP?

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.

What is the meaning of {} in Java?

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.


1 Answers

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.

like image 106
Barmar Avatar answered Sep 20 '22 02:09

Barmar