Home  >  Article  >  Backend Development  >  A problem with singleton mode, why is static $db = null only executed once?

A problem with singleton mode, why is static $db = null only executed once?

WBOY
WBOYOriginal
2016-09-08 08:43:551139browse

<code><?php
require_once("DB.php");

class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      echo '1111';
      $db = new DatabaseConnection();
    return $db;
  }

  private function __construct()
  {
  }
  
}

var_dump(DatabaseConnection::get());
var_dump(DatabaseConnection::get());
?>

为什么 结果只输出一次1111
上面的static $db = null这里不是每执行一次get()就重新对$db付值为null了吗,求解下</code>

Reply content:

<code><?php
require_once("DB.php");

class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      echo '1111';
      $db = new DatabaseConnection();
    return $db;
  }

  private function __construct()
  {
  }
  
}

var_dump(DatabaseConnection::get());
var_dump(DatabaseConnection::get());
?>

为什么 结果只输出一次1111
上面的static $db = null这里不是每执行一次get()就重新对$db付值为null了吗,求解下</code>

Because the parameter is static, you set $db = new DatabaseConnection(); at the end. When you come in for the second time, $db actually changed the first time, so it is not null.
If you don’t believe me, just replace static with public, and it should be Will appear twice

The second time $db is not reassigned, only the first time it is initialized. Please refer to the description of the document link below

staticThe scope of variables is the same as local variables, and the life cycle is the same as global variables.

Statement:
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