【问题标题】:Singleton pattern no more working with php 8.1单例模式不再使用 php 8.1
【发布时间】:2022-07-26 03:55:35
【问题描述】:

这是一些适用于 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 self(); // or new static()
        }
        return $instance;
    }
}

class B extends A
{
    public $name = "My name is B";
}

B::instance()->name;
A::instance()->name;

现在,将此代码与 php 7.4 一起使用将给出:

“我叫 B”

“我是A”

使用 php 8.1 运行时会给出:

“我叫 B”

“我叫 B”

我怀疑 php 开发人员有充分的理由进行此更改,我知道单例模式已被弃用,但我需要使用该代码而不返回 php 7.4。

【问题讨论】:

    标签: php


    【解决方案1】:

    这里有一些好消息,在尽我所能提出我的问题的同时,我找到了解决方案!

    我不需要A类,我只需要一堆类来扩展A。所以解决方案是将方法和单例行为保留在抽象类中

    <?php
    
    abstract class A
    {
        private function __construct() {}
    
        public static function instance()
        {
            static $instance;
            if (!$instance) {
                $instance = new self(); // or new static()
            }
            return $instance;
        }
    }
    
    class B extends A
    {
        public $name = "My name is B";
    }
    
    class C extends A
    {
        public $name = "My name is C";
    }
    
    B::instance()->name;
    C::instance()->name;
    

    这行得通!

    感谢所有在这里分享他们知识的开发者,感谢看到光明的魔力,让您花一些时间清楚地解释您遇到的问题:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 2014-12-26
      • 2012-09-25
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多