I have a main class with the singleton function instance() and the associated variable $instance. Now I create several subclasses and let the main class inherit. I do not re-define the singleton function and variable, because of the useful inheritance. Unfortunately, each instance points to the 1st subclass. Only when in the subclasses the $instance variable is initialized to null it works, but why? With the keywords static and not self, the scope should remain in the subclass.
Here is the source code for a better understanding of what I mean:
// PHP Version 7.0
// Don't work as expected:
class base1
{
/*
* Instance of class
* mixed
*/
protected static $instance = null;
/*
* For Singleton Pattern
*/
public static function instance() {
if ( null == static::$instance ) {
static::$instance = new static();
}
return static::$instance;
}
public function test()
{
$test = "base1";
var_dump($test);
}
}
class sub11 extends base1
{
public function test()
{
$test = "base1 -> sub11";
var_dump($test);
}
}
class sub12 extends base1
{
public function test()
{
$test = "base1 -> sub12";
var_dump($test);
}
}
$sub11 = sub11::instance();
$sub12 = sub12::instance();
$sub11->test();
$sub12->test();
// Output:
// string(14) "base1 -> sub11"
// string(14) "base1 -> sub11" // It's not different!!!
// Work as expected:
class sub21 extends base1
{
/*
* Instance of class
* mixed
*/
protected static $instance = null; // Is needed, but why?
public function test()
{
$test = "base1 -> sub21";
var_dump($test);
}
}
class sub22 extends base1
{
/*
* Instance of class
* mixed
*/
protected static $instance = null; // Is needed, but why?
public function test()
{
$test = "base1 -> sub22";
var_dump($test);
}
}
$sub21 = sub21::instance();
$sub22 = sub22::instance();
$sub21->test();
$sub22->test();
// Output:
// string(14) "base1 -> sub21"
// string(14) "base1 -> sub22" // This is correct !