开发者

Constants in PHP5

I have a class in which I want to define 开发者_Python百科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?


I understand you want to assign a mathematical expression to a constant.

Like:

const FOO = 2.0*pi();

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:

static public function foo()
{
    return  2.0*pi();
}


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:

const FOO = M_PI*2;

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜