Tobia
Tobia

Reputation: 9506

Constant in PHP class and "static" keyword

Please consider this code:

    class App {

        const ALERT_ERROR=1;
        const ALERT_WARN=2;
        const ALERT_INFO=3;

        public static function alert($title,$type=ALERT_ERROR) {        
            switch ($type){
                default:                
                case static::ALERT_ERROR:
                    $class="alert-danger"; break;
                case static::ALERT_WARN:
                    $class="alert-warning"; break;
                case static::ALERT_INFO:
                    $class="alert-info"; break;
            }
            ...
        }
    }

I have some trouble with the static::constant syntax inside the switch. I some PHP webserver it is recognized as correct value (as defined in const ALERT_ERROR) in other server I had to remove the static:: prefix and leave only the constant name. But with this way the first webserver doesn't work...

The first php version is 5.4.7 the second is 5.4.37... but I don't think this is version problem.

The problem is that if I run this code:

App::alert("test",App::ALERT_INFO);

the $class is set a "alert-danger" as default, and the App::ALERT_INFO constant is not recognized. If I add static:: prefix the constant is recognized from one webserver and not from the other and viceversa if I remove it.

The notice thrown is: Use of undefined constant ALERT_ERROR - assumed 'ALERT_ERROR'

EDIT after the answer

The problem was not in the switch cases but in the default parameter. That was assumed as "ALERT_ERROR" string and so only the default switch was got.

Upvotes: 4

Views: 3160

Answers (1)

Maks3w
Maks3w

Reputation: 6429

You have to add the static keyword to the constant used as default value.

public static function alert($title, $type=static::ALERT_ERROR) {
  // ....
}

But static is only determined at runtime. So if static behaviour is really needed then:

public static function alert($title, $type=null) {
  if ($type === null) {
      $type = static::ALERT_ERROR;
  }
  // ...
}

If static is not really necessary then replace all static:: as self::

   public static function alert($title, $type=self::ALERT_ERROR) {        
    switch ($type){
        default:                
        case self::ALERT_ERROR:
            $class="alert-danger"; break;
        case self::ALERT_WARN:
            $class="alert-warning"; break;
        case self::ALERT_INFO:
            $class="alert-info"; break;
    }
    ....
}

Upvotes: 13

Related Questions