PHP不允许对象实例化多次 [英] PHP Don't allow object to instantiate more than once

查看:106
本文介绍了PHP不允许对象实例化多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,它被许多其他类继承。我希望有这样的,而不是每次重新实例化(__construct())同一个类,让它只初始化一次,并利用以前继承的类的属性。

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.

任何建议

推荐答案

这是一个Singleton构造:

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;
    }
}

我创建了构造函数和 __clone() private final ,以阻止人们克隆并直接实现。你可以通过 MyClass :: getInstance()获取Singleton实例

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()

如果你想要一个抽象base-singleton类请查看以下内容: https:// github。 com / WoltLab / WCF / blob / master / wcfsetup / install / files / lib / system / SingletonFactory.class.php

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

这篇关于PHP不允许对象实例化多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆