Home > Backend Development > PHP Tutorial > PHP单例模式疑惑

PHP单例模式疑惑

WBOY
Release: 2016-06-06 20:39:07
Original
1074 people have browsed it

比如下边这个类,这个是我现在常用的代码:

<code><?php class Instance{

    public static $_database;

    public static function Database($_collection=null){
        if(self::$_database === NULL){
            require 'Database.php';
            self::$_database = new Database;
        }
        if($_collection) return self::$_database->collection($_collection);
        else return self::$_database;
    }

}

?>
</code>
Copy after login
Copy after login

如果我执行下边的代码,那么到底是 new 了 Database 几次?到底有没有起到单例的作用?

<code>$collection1 = Instance::Database('test1');
$collection2 = Instance::Database('test2');
$collection3 = Instance::Database('test3');
</code>
Copy after login
Copy after login

回复内容:

比如下边这个类,这个是我现在常用的代码:

<code><?php class Instance{

    public static $_database;

    public static function Database($_collection=null){
        if(self::$_database === NULL){
            require 'Database.php';
            self::$_database = new Database;
        }
        if($_collection) return self::$_database->collection($_collection);
        else return self::$_database;
    }

}

?>
</code>
Copy after login
Copy after login

如果我执行下边的代码,那么到底是 new 了 Database 几次?到底有没有起到单例的作用?

<code>$collection1 = Instance::Database('test1');
$collection2 = Instance::Database('test2');
$collection3 = Instance::Database('test3');
</code>
Copy after login
Copy after login

你在new的前面加个echo调试一下不就知道了?

如果你不愿意动手,那么答案是:只new了一次,之后调用的时候 if(self::$_database === NULL)就为false了,不会再执行到new

调用一次,就new了一次

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template