Reputation: 2214
For my project I've wrote a basic controller class:
<?php
abstract class Controller
{
static $__instance = null;
protected function __construct()
{
}
final private function __clone()
{
}
public static function getInstance()
{
$class = get_called_class();
return self::$__instance ? self::$__instance : (self::$__instance = new $class());
}
}
?>
Now every controller does inheritance from this controller.
Like this:
<?php
include_once 'model/page.php';
include_once 'view/page.php';
class PageController extends Controller
{
private $m_model = null;
private $m_view = null;
private $m_id;
protected function __construct()
{
parent::__construct();
$this->m_id = uniqid();
$this->m_model = new PageModel();
$this->m_view = new PageView();
}
public function preparePage()
{
echo 'Hello';
}
}
?>
And in my index.php I got this: $user = UserController::getInstance(); $page = PageController::getInstance(); var_dump($page);
The problem is that the var_dump($page)
shows that the variable $page is type of UserController, but why? It should be of the type PageController. Any ideas?
Upvotes: 0
Views: 54
Reputation: 522626
Because there's only one self::$__instance
which is shared among all classes that inherit from Controller
. You can use an array to keep track of multiple instances:
return self::$__instance[$class] ? self::$__instance[$class] : (self::$__instance[$class] = new $class());
But really, singleton patterns are frowned upon. You should instantiate new PageController
once at a defined location and inject it down where it is needed. Then there's no need for this static singleton constructor.
Upvotes: 3