简体   繁体   中英

PHP : Singleton dessign pattern or static class

I use from joomla.
I have a custom library in joomla.
We for avoid excessive memory,use static classes like :

class foo
{
    publc static function hello()
    {
        return "HI";
    }
}

And call it with:

foo::hello()

It's best way?
We want to use the functions in the class without any instance.any technical reason for that?
How singleton?

An instance doesn't use memory by itself. What uses memory are the file and the instance info. If you use static classes, you will use the same amount of memory. This is an extreme way of optimizing your code. Not really good, but i will give you points for trying.

Just don't put the functions in a class at all. This isn't Java.

function hello() {
    return "HI";
}

This is one of those design patterns which is good to learn, has good intentions but has inherent weaknesses which make experienced programmers initiate gag-reflexes when it is mentioned. In short, over-use of the singleton pattern will inhibit growth and the re usability of your code as the project grows. The basic intent of the singleton pattern to prevent multiple instantiations of the same object as various sections of a web framework access your singleton throughout a single page rendering.

If you're at the point of wanting to use patterns to simplify your code, that is a good thing; but be sure to apply the right patterns to the correct problems. Examples being Registry, Factory, Abstract Factory and Dependency Injection being a few I would explore when starting out.

Finally, here is an example of a singleton class for PDO connections from one of my many php books, PHP Master: write cutting edge code.

class Database extends PDO
{
    private static $_instance = null;

    private function __construct() {
        parent::__construct(APP_DB_DSN, APP_DB_USER, APP_DB_PASSWORD);
    }

    public static function getInstance() {
        if(!(self::$_instance instanceof Database)) {
            self::$_instance = new Database();
        }

        return self::$_instance;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM