215

我有这个代码:

private static $dates = array(
  'start' => mktime( 0,  0,  0,  7, 30, 2009),  // Start date
  'end'   => mktime( 0,  0,  0,  8,  2, 2009),  // End date
  'close' => mktime(23, 59, 59,  7, 20, 2009),  // Date when registration closes
  'early' => mktime( 0,  0,  0,  3, 19, 2009),  // Date when early bird discount ends
);

这给了我以下错误:

解析错误:语法错误,第 19 行 /home/user/Sites/site/registration/inc/registration.class.inc 中的意外 '(', expecting ')'

所以,我想我做错了什么......但如果不是那样,我该怎么做呢?如果我用常规字符串更改 mktime 内容,它就可以工作。所以我知道我可以像那样做..

有人有一些指示吗?

4

9 回答 9

353

PHP 无法解析初始化程序中的重要表达式。

我更喜欢通过在定义类之后添加代码来解决这个问题:

class Foo {
  static $bar;
}
Foo::$bar = array(…);

或者

class Foo {
  private static $bar;
  static function init()
  {
    self::$bar = array(…);
  }
}
Foo::init();

PHP 5.6现在可以处理一些表达式。

/* For Abstract classes */
abstract class Foo{
    private static function bar(){
        static $bar = null;
        if ($bar == null)
            bar = array(...);
        return $bar;
    }
    /* use where necessary */
    self::bar();
}
于 2009-03-28T23:50:04.017 回答
33

如果您可以控制类加载,则可以从那里进行静态初始化。

例子:

class MyClass { public static function static_init() { } }

在您的类加载器中,执行以下操作:

include($path . $klass . PHP_EXT);
if(method_exists($klass, 'static_init')) { $klass::staticInit() }

一个更重量级的解决方案是使用带有 ReflectionClass 的接口:

interface StaticInit { public static function staticInit() { } }
class MyClass implements StaticInit { public static function staticInit() { } }

在您的类加载器中,执行以下操作:

$rc = new ReflectionClass($klass);
if(in_array('StaticInit', $rc->getInterfaceNames())) { $klass::staticInit() }
于 2010-12-17T11:24:07.307 回答
23

与其想办法让静态变量工作,我更喜欢简单地创建一个 getter 函数。如果您需要属于特定类的数组并且实现起来更简单,这也很有帮助。

class MyClass
{
   public static function getTypeList()
   {
       return array(
           "type_a"=>"Type A",
           "type_b"=>"Type B",
           //... etc.
       );
   }
}

无论您在哪里需要该列表,只需调用 getter 方法即可。例如:

if (array_key_exists($type, MyClass::getTypeList()) {
     // do something important...
}
于 2011-10-16T15:20:19.903 回答
11

我结合了 Tjeerd Visser 和porneL 的答案。

class Something
{
    private static $foo;

    private static getFoo()
    {
        if ($foo === null)
            $foo = [[ complicated initializer ]]
        return $foo;
    }

    public static bar()
    {
        [[ do something with self::getFoo() ]]
    }
}

但更好的解决方案是取消静态方法并使用单例模式。然后你只需在构造函数中进行复杂的初始化。或者将其设为“服务”并使用 DI 将其注入到任何需要它的类中。

于 2013-10-21T18:41:06.863 回答
10

这太复杂了,无法在定义中设置。您可以将定义设置为 null,然后在构造函数中检查它,如果它没有被更改 - 设置它:

private static $dates = null;
public function __construct()
{
    if (is_null(self::$dates)) {  // OR if (!is_array(self::$date))
         self::$dates = array( /* .... */);
    }
}
于 2009-03-28T23:13:10.563 回答
4

您不能在这部分代码中进行函数调用。如果您创建了一个 init() 类型的方法,该方法在任何其他代码之前执行,那么您将能够填充该变量。

于 2009-03-28T22:53:04.980 回答
4

最好的方法是创建这样的访问器:

/**
* @var object $db : map to database connection.
*/
public static $db= null; 

/**
* db Function for initializing variable.   
* @return object
*/
public static function db(){
 if( !isset(static::$db) ){
  static::$db= new \Helpers\MySQL( array(
    "hostname"=> "localhost",
    "username"=> "root",
    "password"=> "password",
    "database"=> "db_name"
    )
  );
 }
 return static::$db;
}

然后你可以做 static::db(); 或 self::db(); 从任何地方。

于 2013-09-03T14:52:50.570 回答
4

在 PHP 7.0.1 中,我可以这样定义:

public static $kIdsByActions = array(
  MyClass1::kAction => 0,
  MyClass2::kAction => 1
);

然后像这样使用它:

MyClass::$kIdsByActions[$this->mAction];
于 2017-01-26T10:18:28.943 回答
-1

这是一个希望有用的指针,在代码示例中。注意初始化函数如何只被调用一次。

此外,如果你反转调用StaticClass::initializeStStateArr()$st = new StaticClass()你会得到相同的结果。

$ cat static.php
<?php

class StaticClass {

  public static  $stStateArr = NULL;

  public function __construct() {
    if (!isset(self::$stStateArr)) {
      self::initializeStStateArr();
    }
  }

  public static function initializeStStateArr() {
    if (!isset(self::$stStateArr)) {
      self::$stStateArr = array('CA' => 'California', 'CO' => 'Colorado',);
      echo "In " . __FUNCTION__. "\n";
    }
  }

}

print "Starting...\n";
StaticClass::initializeStStateArr();
$st = new StaticClass();

print_r (StaticClass::$stStateArr);

产生:

$ php static.php
Starting...
In initializeStStateArr
Array
(
    [CA] => California
    [CO] => Colorado
)
于 2013-07-11T18:23:54.193 回答