Re: Static initialization block support in Class?
| From: | Richard Quadling | Date: | Tue, 17 Aug 2010 08:04:26 +0000 |
| Subject: | Re: Static initialization block support in Class? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-49436@lists.php.net to get a copy of this message | ||
On 17 August 2010 08:39, Jingcheng Zhang <diogin@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.