构造函数如何在没有创建对象的情况下调用?为什么构造函数没有以相同的方式再次调用?

我使用PHP 7.1.11构造函数如何在没有创建对象的情况下调用?为什么构造函数没有以相同的方式再次调用?

考虑下面的工作代码和它的输出:

<?php 

class butto {

public static $instance;

private function __construct() {

echo 'Contruct of butto class called</br>';

}

public static function get_instance() {

if(!static::$instance instanceof static) {

static::$instance = new static();

}

return static::$instance;

}

public function test() {

echo 'test function called</br>';

}

}

class B extends butto {

public static $instance;

protected function __construct() {

echo 'Construct of Class B called</br>';

}

public static function get_class_name() {

return __CLASS__;

}

}

butto::get_instance()->test();

B::get_instance()->test();

B::get_instance()->test();

/*Output : Contruct of butto class called

test function called

Construct of Class B called

test function called

test function called*/

?>

如果你看一下代码观察,你会知道,无论是类的构造函数即使没有创建任何类的对象也会被调用。

即使我静态访问任何静态方法,构造函数也会被调用。到目前为止,我知道构造函数只能在创建对象时调用,因为构造函数的目的是将初始值设置为对象属性,并在创建对象时立即使用。

那么这怎么可能?以这种方式使用构造函数有什么好处,即访问时不需要创建对象?

考虑下面的代码行:

B::get_instance()->test(); 

B::get_instance()->test();

我的问题是,为什么B类的构造函数获取调用仅前行?

它应该被再次调用第二行。

为什么它表现得如此怪异?

回答:

因为您的get_instance()本身具有这种逻辑。您正在将实例分配给您的静态变量。静态变量在同一类的不同实例之间“共享”。因此,当您第一次调用函数get_instance()时,您正在创建对象并将其存储在您的静态变量$instance中。下次当你调用相同的函数时,你的if条件结果是错误的,因此不需要创建一个新的对象/实例。再看看下面的代码:

public static function get_instance() { 

if(!static::$instance instanceof static) {

static::$instance = new static();

}

return static::$instance;

}

它不是行为怪异的方式,但它的行为表现为你的代码要求它的行为。

以上是 构造函数如何在没有创建对象的情况下调用?为什么构造函数没有以相同的方式再次调用? 的全部内容, 来源链接: utcz.com/qa/259506.html

回到顶部