我使用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()'中构造对象!那么,你在说什么?!此外,'static :: $ instance'和'new static()',也可以引用'butto'的任何潜在衍生物(与'self :: $ instance'和'new self()'对比),所以解释为什么他们各自的构造函数也被调用,如果从他们自己的上下文中调用。 –
另请参阅https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5的答案。 – localheinz