最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Curly braces syntax for addressing a class constant with a variable - Stack Overflow

programmeradmin4浏览0评论

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 0
Add a comment  | 

2 Answers 2

Reset to default 1

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

发布评论

评论列表(0)

  1. 暂无评论