douwayuan3063 2012-01-24 21:36
浏览 46
已采纳

PHP不允许对象多次实例化

I have an abstract class that is inherited by a number of other classes. I'd like to have it so that instead of re-instantiating (__construct()) the same class each time, to have it only initialize once, and utilize the properties of the previously inherited classes.

I'm using this in my construct:

function __construct() {
         self::$_instance =& $this;

         if (!empty(self::$_instance)) {
            foreach (self::$_instance as $key => $class) {
                     $this->$key = $class;
            }
         }
}

This works - sort of, I'm able to get the properties and re-assign them, but within this, I also want to call some other classes, but only one time.

Any suggestions for a better way to go about doing this?

  • 写回答

2条回答 默认 最新

  • donglvlao8367 2012-01-24 21:40
    关注

    Thats a Singleton construct:

    class MyClass {
        private static $instance = null;
        private final function __construct() {
            //
        }
        private final function __clone() { }
        public final function __sleep() {
            throw new Exception('Serializing of Singletons is not allowed');
        }
        public static function getInstance() {
            if (self::$instance === null) self::$instance = new self();
            return self::$instance;
        }
    }
    

    I made the constructor and __clone() private final to hinder people from cloning and directly instanciating it. You can get the Singleton instance via MyClass::getInstance()

    If you want an abstract base-singleton class have a look at this: https://github.com/WoltLab/WCF/blob/master/wcfsetup/install/files/lib/system/SingletonFactory.class.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度