문제

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.

도움이 되었습니까?

해결책

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;
    
    }
    

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top