开发者

php static array initialization workaround

开发者 https://www.devze.com 2023-03-23 12:30 出处:网络
I\'m not sure what I should be searching to figure out this issue, so I\'ll show the code and describe the issue:

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开发者_Python百科 would reduce the overhead of the __construct function; however, I can't really see a single method call being significant savings.


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

0

精彩评论

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

关注公众号