doufeng1249 2011-07-28 23:00
浏览 155
已采纳

php静态数组初始化解决方法

I'm not sure what I should be searching to figure out this issue, so I'll show the code and describe the issue:

PHP Code:

<?php
class Foo
{
  private static
    $defaultSettings = array(
      'bar' => new Baz() //error here
    );

  private
    $settings;

  public function __construct( $options = null )
  {
    $this->settings = isset( $options ) ? array_merge( self::$defaultSettings, $options ) : self::$defaultSettings;
  }
}

class Baz
{
  ...code...
}

The Error:

Parse error: syntax error, unexpected T_NEW in [filename] on line [number]

What I'd like to do is have Foo::$defaultSettings contain an instance of an object, but I can't initialize the object when I create the array.

Is there a simpler way around this issue than a static initializer?

Static initializer code for Foo:

//self::init() would be called on the first line of __construct
private static function init()
{
  static $initialized;

  if ( !$initialized )
  {
    $initialized = true;
    self::$defaultSettings['bar'] = new Baz();
  }
}

I feel like there should be a simpler way around this issue than having to run an initializer.


Edit to add:

I could also make the initializer function public and call it immediately after the class definition as Foo::init(); which would reduce the overhead of the __construct function; however, I can't really see a single method call being significant savings.

  • 写回答

1条回答 默认 最新

  • dqp99585 2011-07-28 23:15
    关注

    Class properties cannot evaluate or instantiate anything, unfortunately. The closest you can do is run something from your constructor.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了