Although the whole solution is bad, you can have a private static method which is called in each other public static method.
This is not a constructor, and it's normally, because the constructor is used to construct and object, and you don't have one in static context.
So, for firing a common functionality after each static call, you can use:
class Example {
private static function common() {
echo 'called';
}
public static function method1() {
self::common();
echo "</br> method1;";
}
public static function method2() {
self::common();
echo "</br> method2;";
}
}
Example::method2();
Which results into
called
method2;
You can also build your object into the static method
class Example {
private function __construct() {
echo 'contructor called';
}
public static function method1() {
$self = new self();
echo "</br> method1;";
}
public static function method2() {
$self = new self();
echo "</br> method2;";
}
}
Example::method1();
Results into:
contructor called
method1;
The problem here is that each method will can new instance of the constructor.
You can use the Singleton pattern as suggested, in order to have shared instance of the class in all your static methods.
class Example {
private static $_inst = null;
private $_x = 0;
private function __construct() {
echo 'contructor called';
}
private static function getInstance() {
if(self::$_inst == null) {
self::$_inst = new self();
}
return self::$_inst;
}
public static function method1() {
self::getInstance();
self::getInstance()->_x = 100;
echo "</br> method1;";
}
public static function method2() {
self::getInstance();
echo self::getInstance()->_x;
echo "</br> method2;";
}
}
Example::method1();
Example::method2();
Which will result into:
contructor called
method1;100
method2;
So the value of instance variable $_x
is saved when method2()
is called, but the constructor is not called second time as you can see there is only one contructor called
in the result.
And, to repeat myself, this whole idea is horrible.