views:

1086

answers:

4

I want to create a static class in PHP and have it behave like it does in C#, so

  1. Constructor is automatically called on the first call to the class
  2. No instantiation required

Something of this sort...

static class Hello {
    private static $greeting = 'Hello';

    private __construct() {
        $greeting .= ' There!';
    }

    public static greet(){
        echo $greeting;
    }
}

Hello::greet(); // Hello There!
+12  A: 

You can have static classes in PHP but they don't call the constructor automatically (if you try and call self::__construct() you'll get an error).

Therefore you'd have to create an initialize() function and call it in each method:

<?php

class Hello
{
    private static $greeting = 'Hello';
    private static $initialized = false;

    private static function initialize()
    {
     if (self::$initialized)
      return;

        self::$greeting .= ' There!';
     self::$initialized = true;
    }

    public static function greet()
    {
     self::initialize();
        echo self::$greeting;
    }
}

Hello::greet(); // Hello There!


?>
Greg
I quite often do this just to wrap functions up all in one place. IE Utility::doSomethingUseful();
smack0007
+4  A: 

you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...

see http://stackoverflow.com/questions/432192/singleton-in-php

Andreas Niedermair
A: 

///////////////

class A{

//attributes and methods here.....

}

//////////////

final Class B{

static $staticVar=new A();

}

//i got an error with this why? how should i do it if i want to create an static instance of a class inside a static class?

reycfernandez
A: 
final Class B{

    static $staticVar;
    static function getA(){
        self::$staticVar = New A;
    }
}

the stucture of b is calld a singeton handler you can also do it in a Class a{

    static $instance;
    static function getA(...){
        if(!isset(self::$staticVar)){
            self::$staticVar = New A(...);
        }
        return self::$staticVar;
    }
}

this is the singleton use $a = a::getA(...);