在php中使用自定义类初始化静态成员


Initialize static member with custom class in php

由于PHP中没有枚举,我尝试这样做:

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

问题是,我得到一个解析错误,如果我运行脚本:

Parse error: syntax error, unexpected T_NEW 

我" working it around " 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;
    }
}

它工作,但我不是很满意。谁能解释一下,为什么我不能做静态$xyz = new xyz ();对于这个问题有更好的解决方法吗?

我知道这很烦人。我像这样解

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

它有点类似于java的"静态代码块"(或者不管他们叫什么^^)

无论如何,该文件只能包含一次(因为发生了"class already define"错误),所以您可以确定,类下面的代码也只执行一次。

作为一种优化,您可以将对象实例存储为静态字段,这样您就不必在每次调用静态方法时都创建一个新对象:

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

但是,当您第一次定义一个类字段时,您不能将一个新的对象实例分配给该类字段,这是很烦人的。(

引用 static 手册页:

和其他PHP静态变量一样,静态属性只能是使用字面值或初始化恒定的;表达式是不允许的。虽然你可以初始化一个静态属性设置为整数或数组实例),则不能初始化它到另一个变量,到一个函数返回值,或返回一个对象。

这就是为什么你不能做

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