> 
> Most of these examples are just crying out to be real objects, not
> static classes. You might not want to be creating them every time you
> use them, but that's what patterns like Singletons and Dependency
> Injection are for.
> 

I really disagree to this. Singletons are a typical FactoryPattern, none
of the examples except the LogAdapter itself are doing implementation of
a factory. They are just initialize some computed static variables once
in the live time of the class mostly for internal usage of the class.
That is nearly like initializing a class constant, but in my opinion a
constant should not have a "complex" algorithm (For example conditions
or read from filesystem). That should be encapsulated inside a proper
method body.

In use case 1 Dependency Injection maybe another solution but does not
exactly do what I want to do.

> 
>> 1. Nearly all of my classes have a static LogAdapter $LOG which has to
>> be intialized with Classname once.
>>
>> class A {
>>      private static $LOG;
>>
>>      public static function __static() {
>>          self::$LOG = LogAdapter::getLogger(self::class);
>>      }
>> } A::__static();
>>
>> The LogAdapter by it selfs although have a __static() method to prepare
>> the Log4PHP-Framework I'm using.
> 
> This particular example could be achieved with a static getLogger()
> method, which does the initialisation check the first time the logger is
> needed, rather than the first time class A is needed.
> 

yes that would be another valid pattern. And would be prefered for me if
I use the Logger in 1 or 2 out of 10 class methods, which are not used
very often. But mostly I'm using it in 9 or 10 of 10 methods, which are
invoked several times through lifetime. So doing a null check each time
is a overhead of calculation which can be avoided with this static
constructor pattern.

> 
> To my mind, the creation of a class in memory should not have
> side-effects - you should be able to assume that all your classes exist
> at the same time, before any of your code runs. 


I agree the real creation(/parsing) of the class should have no
side-effects. But the static constructor is not executed at the
creation-time of the class but directly before first access on the
class. That are two totally different moments in the lifecycle of the
class and does not block the possibility to first read all classes
without any side-effects.

> The only justification
> for not acting that way would be Python-style metaclasses, where the
> creation of a class definition was the responsibility of some other
> object, and that's a power to be wielded very carefully.
> 

The static constructor or sometimes although called class constructor is
a well known OOP-pattern implemented by different languages like C#
or Java.

Regards,

-- 
DerOetzi

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to