为了账号安全,请及时绑定邮箱和手机立即绑定

如何初始化静态变量

如何初始化静态变量

PHP
叮当猫咪 2019-08-30 17:36:54
我有这个代码: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中的语法错误,意外'(',期待')'所以,我想我做错了什么......但是如果不是那样的话怎么办呢?如果我用常规字符串更改mktime内容,它就可以工作。所以,我知道我能做到这一点的那种像..有人有指点吗?
查看完整描述

3 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

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();

}


查看完整回答
反对 回复 2019-08-30
?
MM们

TA贡献1886条经验 获得超2个赞

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


例:


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() }


查看完整回答
反对 回复 2019-08-30
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

我没有找到让静态变量工作的方法,而是简单地创建一个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...

}


查看完整回答
反对 回复 2019-08-30
  • 3 回答
  • 0 关注
  • 494 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信