Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用self:$\u instance=new self()有什么意义_Php - Fatal编程技术网

Php 使用self:$\u instance=new self()有什么意义

Php 使用self:$\u instance=new self()有什么意义,php,Php,我正在学习OOP PHP,遇到了以下问题: //Store the single instance private static $_instance; /* Get an instance of the database @return database */ public static function getInstance () { if (!self::$_instance) { self::$_instance = new self();

我正在学习OOP PHP,遇到了以下问题:

//Store the single instance
private static $_instance;

/*
    Get an instance of the database
    @return database
*/
public static function getInstance () {
    if (!self::$_instance) {
        self::$_instance = new self();
    }
    return self::$_instance;
}

$\u实例设置为新的
self()
有什么意义?我知道这行所做的只是创建它所在类的一个新实例,但为什么需要这样做呢?有什么理由需要这样做吗?我甚至在课堂上都不会再叫它了。谢谢你在高级课程中的帮助

其思想是,无论何时在整个代码中调用getInstance(),都会得到相同的实例

这在某些情况下非常有用,因为您只想访问同一个对象。像这样的对象通常可能有一个私有构造函数,它有效地迫使您始终对同一个实例(也称为单例)执行操作


通常人们说“单身是邪恶的”。避免它们是很好的,因为它们会导致重大的设计问题。在某些情况下,它们仍然是一个好主意。

这是单例模式

当您有一个需要初始化和/或拆卸工作的对象,并且该工作只需执行一次时,可以使用该选项

实例缓存强制该类只有一个实例。

工作示例

class Singleton
{
    public $data;

    private static $instance = null;

    public function __construct()
    {
        $this->data = rand();
    }


    public static function getInstance()
    {
        if (is_null(self::$instance))
            self::$instance = new self;

        return self::$instance;
    }


    //no clone
    private function __clone() {}
    //no serialize
    private function __wakeup() {}
}


$singleton = Singleton::getInstance();

echo $singleton->data;
echo '<br>';

$singleton2 = Singleton::getInstance();

echo $singleton2->data;
echo '<br>';
类单例
{
公共数据;
私有静态$instance=null;
公共函数构造()
{
$this->data=rand();
}
公共静态函数getInstance()
{
if(为null(self::$instance))
self::$instance=新self;
返回self::$instance;
}
//没有克隆
私有函数uu clone(){}
//没有连载
私有函数uu wakeup(){}
}
$singleton=singleton::getInstance();
echo$singleton->data;
回声“
”; $singleton2=Singleton::getInstance(); echo$singleton2->data; 回声“
”;
在我看来,这就像是将一个对象分配给另一个对象。@sandepsure,在这里,我对面向对象非常陌生,这个术语让我感到困惑。这被称为。另外。@JoeScotto此链接描述了在php中使用单例模式时的操作方法。它是如何强制它只有一个实例的?我还是很困惑。@JoeScotto一旦你明白你已经回答了你自己的问题。@JoeScotto它实际上根本没有强迫它,除非还有一个私有构造函数。您共享的代码只是确保每次调用时都会得到相同的实例。