Alvarez
Alvarez

Reputation: 1333

Is this php syntax valid? $class->{'something'}()

I was reading a code example of something, and noticed a syntax that isn't familiar to me.

$response = $controller->{'home'}();

Is that a valid php syntax?

Upvotes: 3

Views: 57

Answers (2)

angelcool.net
angelcool.net

Reputation: 2546

Yes it is. The cool thing about it is that you can call object's methods based on values stored in variables:

$whatToExecute = 'home';

$response = $controller->{$whatToExecute}();

Good luck!!

Upvotes: 2

Alex Tartan
Alex Tartan

Reputation: 6826

Yes.

$controller->{'home'}
// same as 
$controller->home 
// used to access a property

And

$controller->{'home'}()
// same as 
$controller->home()
// used to call a method

The main benefit is that, by calling ->{stuff}, you can access properties with different (or strange) names.

Example:

$a = new stdClass();
$a->{'@4'} = 4;

print_r($a);
// stdClass Object
// (
//    [@4] => 4
// )

You can't do $a->@4, but can do $a->{'@4'}

See this, for instance: https://3v4l.org/PaOF1

Upvotes: 4

Related Questions