1

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
Razvan
  • 319
  • 3
  • 11

2 Answers2

4

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();
}
madflow
  • 7,718
  • 3
  • 39
  • 54
1

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.

Zsolt Rácz
  • 103
  • 1
  • 6