开发者

How to get instance of a singleton PHP class while extending it?

I have a specific class in my project that used for load and hold everything else like libraries and modules.

For example;

index.php
---------
require_once "Libs/Damn.php";
$damn = Damn::getInstance();

// Initialize the URI class for handling user's request.
$damn->load('URI');
$damn->load('Modules');
$damn->load('Views');

if($damn->URI->module){
    $damn->Modules->load($damn->URI->module);
} else {
    $damn->Modules->load('main');
}

It is simply load 3 library and looking for a module name in the URL. If it can't find, it'll load the module named as "main" (main.php).

Here is the problem;

When i extend the Damn class in main.php, i can't access to loaded libraries like URI, Modules but i want to. It seems extending a singleton class is not getting instance of the class, just copying it.

I want to be able to use a module class like this;

main.php
--------
<?php
if (!defined('SECURED')) die('Access denied.');

class Main extends Damn {

    public function __construct() {}

    public function index() {
        $开发者_开发问答this->Views->load('test'); //Views library already loaded when Damn initiated.
    }

    public function __destruct() {}

}

?>


You actually don't extend Damn. You create a new class that extends from Damn. Your original class is unaffected, and the data in the singleton instance is not magically copied to a new class.

The best (well, 'A good') solution here, is not to extend Main from Damn, but create a new Main class that uses Damn to manage the models.

It is illogical to change the type of the instance of a singleton based on a property of an earlier instance of the singleton. This smells like bad design :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜