以下是一些适用于 php 7.4 但不适用于 php 8.1 的简单代码:
<?php
class A
{
public $name = "I'm A";
private function __construct() {}
public static function instance()
{
static $instance;
if (!$instance) {
$instance = new static();
}
return $instance;
}
}
class B extends A
{
public $name = "My name is B";
}
echo B::instance()->name . "\n";
echo A::instance()->name . "\n";
Run Code Online (Sandbox Code Playgroud)
现在,在 php 7.4 中使用此代码将给出:
“我叫B”
“我是一个”
使用 php 8.1 运行它时将给出:
“我叫B”
“我叫B”
我怀疑 php 开发人员有充分的理由进行此更改,我知道单例模式在某种程度上已被弃用,但我需要使用该代码而不返回到 php 7.4。
php ×1