Question

I'm new to php.
I'm having a weird scenario where I cannot declare the following inside a function:

const CONST_Example = 1/192;

I'v tried also:

const CONST_Example  = 1;    

Do not work either. I want to be able to save constant float number which is a result of arithmetic expression such as 1/190, etc.

Était-ce utile?

La solution

It is indeed impossible to create that value as a class constant in PHP. You can't declare it like this:

class Foo {

    const CONST_Example = 1/192;

}

because PHP is not able to evaluate expressions while it parses class declarations.
You can also not add the constant to the class after the fact at runtime.

Your options are:

  1. Declare it as regular runtime defined constant:

    define('CONST_Example', 1/192);
    
  2. Use the next best float representation as a literal:

    class Foo {
    
        const CONST_Example = 0.005208333333333333;
    
    }
    

Autres conseils

The first one won't work, but the second one should. Here's an example how you can have your class working with constants

<?php
class Foo {
    const CONST_EXAMPLE = 1;
}

The first one won't work, because of the following reason:

"The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call."

Source: http://php.net/manual/en/language.oop5.constants.php

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top