开发者

Initialize static member with custom class in php

as there are no enums in PHP I tried to do something like this:

class CacheMode{    

    public static $NO_CACHE = new CacheMode(1, "No cache");

    private $id, $title;

    public function getId(){
        return $this->id;
    }

    public function getTitle(){
        return $this->title;
    }

    private function __construct($id, $title){
        $this->id = $id;
        $this->title = $title;
    }
}

The problem is, that I get a parse error if I run the script:

Parse error: syntax error, unexpected T_NEW 

I "worked it aroud" with this:

class CacheMode{     
    public static function NO_CACHE(){
        return new CacheMode(1, __("No cache",'footballStandings'));
    }

    public static function FILE_CACHE(){
        return new CacheMode(2, __("Filecache",'footballStandings'));
    }

    public static function VALUES(){
        return array(self::NO_CACHE(), self::FILE_CACHE());
    }

    private $id, $title;

    public function getId(){
        return $this->id;
    }

    public function getTitle(){
        return $this->title;
    }

    private function __construct($id, $title){
        $this->id = $id;
        $this->title = $title;
    }
}

It works, but I am not r开发者_StackOverflow社区eally happy with it. Can anyone explain, why I can't do the static $xyz = new XYZ(); way or has a better solution for this problem?


Its annoying, I know. I solve it like

class Foo {
  public static $var;
}
Foo::$var = new BarClass;

Its a little bit similar to javas "static code blocks" (or whatever they are called ^^)

The file is only includeable once anyway (because a "class already define" error occurs), so you can be sure, that also the code below the class is executed once.


As an optimization, you could store the object instance as a static field, so that you are not creating a new object every time the static method is called:

private static $noCache;
public static function NO_CACHE(){
  if (self::$noCache == null){
    self::$noCache = new CacheMode(1, __("No cache",'footballStandings'));
  }
  return self::$noCache;
}

But yes, it is annoying that you cannot assign a new object instance to a class field when you first define the field. :(


Quoting the manual page of static :

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

That is why you cannot do

public static $NO_CACHE = new CacheMode(1, "No cache");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜