Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 504
Alvarez Avatar asked Feb 12 '26 17:02

Alvarez


1 Answers

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

like image 81
Alex Tartan Avatar answered Feb 14 '26 07:02

Alex Tartan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!