On 17 August 2010 08:39, Jingcheng Zhang <dio...@gmail.com> wrote: > Hello internals, > > I wonder whether it is possible to implement "static initialization block" > feature in PHP, for example: > > <?php > class Foo { > > } > class Bar { > public static $baz = 'baz'; > public static $foo; > static { > // After loading this file, self::$foo is initialized as a Foo > instance. > self::$foo = new Foo(); > } > } > ?> > > Currently we have to do this outside the class definition as static variable > initialization is only limited to constant values. > However in some circumstance, "dynamic" initialization of static variable is > expected and meaningful. > > Thanks in advance! > > -- > Best regards, > Jingcheng Zhang > P.R.China >
Implementing a singleton method is a common solution and one that is well understood and documented. Another option would be to put the initialisation immediately after the class definition, so once the class is loaded, a static instance is prepared. This saves the consumer of the class from having to do 1 additional line of code. Or you could load the public static methods with a JIT call to prepare the static instance. Overhead is that every call will have to test self::$instance There is probably some argument against "statics" being "dynamic" though ... not my area of expertise to argue either way. -- Richard Quadling. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php