PHP5 中的常量
我有一个类,我想在其中定义其他类使用的一些常量。 const 关键字对我来说还不够,因为我想使用像 2.0 * pi() 这样的数学表达式作为常量。是如何做到的?
I have a class in which I want to define some constants used by other classes. The const keyword isn't enough for me because I want for example to use a mathematical expression like 2.0 * pi() as a constant. How is done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道您想将数学表达式分配给常量。
例如:
PHP 常量只能包含标量值。如果您希望其他类使用共享信息,则必须为此使用静态函数/方法。
例子:
I understand you want to assign a mathematical expression to a constant.
Like:
PHP constants can only contain scalar values. If you want other classes to use shared information, you will have to use static functions/methods for this.
Example:
实际上,PHP 5.6 中实现了类似的功能,您可以将各种表达式的结果分配给类常量。
您可以在这里阅读更多相关信息:
http://php.net/manual/en/migration56.new-features.php#migration56.new-features.const-scalar-exprs
和这里:
https://wiki.php.net/rfc/const_scalar_exprs
根据以下规定,仍然不允许分配函数结果文档,但是与您的示例具有相同结果的以下表达式应该完全有效:
请注意,PHP 5.6 还没有稳定的版本,因此目前不建议在生产中使用它。
Actually something similar is implemented in PHP 5.6 where you can assign results of various expressions to class constants.
You can read more about it here:
http://php.net/manual/en/migration56.new-features.php#migration56.new-features.const-scalar-exprs
and here:
https://wiki.php.net/rfc/const_scalar_exprs
Assigning results of functions is still not allowed according to the documentation, however the following expression that has the same result as your example should be completely valid:
Be advised that PHP 5.6 does not have a stable release yet, so it is not recommended for now to use it in production.