我可以在 PHP 中使用字符串连接来定义类 CONST 吗?
我知道您可以使用字符串连接来创建彼此之间的全局常量:
define('FOO', 'foo');
define('BAR', FOO.'bar');
echo BAR;
将打印“foobar”。
但是,我在尝试使用类常量执行相同操作时遇到错误。
class foobar {
const foo = 'foo';
const foo2 = self::foo;
const bar = self::foo.'bar';
}
foo2 的定义没有问题,但声明 const bar 会出错
解析错误:语法错误,意外的“.”,期望“,”或“;”
我也尝试过使用像 sprintf() 这样的函数,但它不喜欢左括号,也不喜欢字符串连接符“.”。
那么,除了像 foo2 这样的简单集合案例之外,还有什么方法可以相互创建类常量呢?
I know that you can create global constants in terms of each other using string concatenation:
define('FOO', 'foo');
define('BAR', FOO.'bar');
echo BAR;
will print 'foobar'.
However, I'm getting an error trying to do the same using class constants.
class foobar {
const foo = 'foo';
const foo2 = self::foo;
const bar = self::foo.'bar';
}
foo2 is defined without issue, but declaring const bar will error out
Parse error: syntax error, unexpected '.', expecting ',' or ';'
I've also tried using functions like sprintf() but it doesn't like the left paren any more than the string concatenator '.'.
So is there any way to create class constants in terms of each other in anything more than a trivial set case like foo2?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
唯一的方法是定义()一个表达式,然后在类中使用该常量
另一个选择是访问 bugs.php.net 并恳请他们解决这个问题。
The only way is to define() an expression and then use that constant in the class
Another option is to go to bugs.php.net and kindly ask them to fix this.
恕我直言,这个问题值得 PHP 5.6+ 的答案,感谢 @jammin comment
从 PHP 5.6 开始,您可以为常量定义静态标量表达式:
虽然它不是问题的一部分,但应该是意识到实施的局限性。以下内容不起作用,尽管它是静态内容(但可能在运行时被操纵):
有关更多信息,请查看: https://wiki.php.net/rfc/const_scalar_exprs 和 http://php.net/manual/en/language.oop5.constants.php
Imho, this question deserves an answer for PHP 5.6+, thanks to @jammin comment
Since PHP 5.6 you are allowed to define a static scalar expressions for a constant:
Although it is not part of the question, one should be aware of the limits of the implementation. The following won't work, although it is static content (but might be manipulated at runtime):
For further information take a look at: https://wiki.php.net/rfc/const_scalar_exprs and http://php.net/manual/en/language.oop5.constants.php
对于此类内容,请始终参考可靠的手册。
关于常量:
所以......“不”就是答案:D
Always fall back to the trusty manual for stuff like this.
Regarding constants:
So... "no" would be the answer :D
对于类常量,除了常量表达式之外,您不能分配任何内容。引用 PHP 手册:
“该值必须是常量表达式,不是(例如)变量、属性、数学运算的结果或函数调用。”
For class constants, you can't assign anything other than a constant expression. Quoting the PHP manual:
"The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call. "
这可能不是您直接寻找的,但我遇到了这个线程,所以这是我用于解决我遇到的问题的解决方案(基于@user187291的答案):
似乎效果很好!
This may not be directly what you're looking for, but I came across this thread, so here is a solution that I used for an issue I was having (based off of @user187291's answer):
Seems to work great!