The following PHP code is perfectly valid and runs without an error:
<?php
class MyClass {
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
$identifier = 'CONST_VALUE';
echo $classname::{$identifier}, "\n";
with the following output:
A constant value
So what is it and how it works? If you can reference me to the PHP documentation on the matter, it would be lovely.
The following PHP code is perfectly valid and runs without an error:
<?php
class MyClass {
const CONST_VALUE = 'A constant value';
}
$classname = 'MyClass';
$identifier = 'CONST_VALUE';
echo $classname::{$identifier}, "\n";
with the following output:
A constant value
So what is it and how it works? If you can reference me to the PHP documentation on the matter, it would be lovely.
Share Improve this question edited Mar 27 at 8:00 Your Common Sense 158k42 gold badges225 silver badges368 bronze badges asked Mar 27 at 7:38 Denis KulaginDenis Kulagin 8,96719 gold badges71 silver badges137 bronze badges 02 Answers
Reset to default 1The strings documentation isn't the right place to look, the variable variables documentation is:
In order to use variable variables with arrays, an ambiguity problem has to be resolved. That is, if the parser sees
$$a[1]
then it needs to know if$a[1]
was meant to be used as a variable, or if$$a
was wanted as the variable and then the[1]
index from that variable. The syntax for resolving this ambiguity is:${$a[1]}
for the first case and${$a}[1]
for the second.Class properties may also be accessed using variable property names. [..]
Curly braces may also be used to clearly delimit the property name.
Constants aren't explicitly mentioned, but they work the same way.
The exposed behaviour is available since PHP v8.3.0. It is demonstrated in Example #6: Fetch class constant syntax, in the documentation page of Class Constants.