Home > Article > Backend Development > A problem with singleton mode, why is static $db = null only executed once?
<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>
<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
static
The scope of variables is the same as local variables, and the life cycle is the same as global variables.