实例作为静态类属性 [英] Instance as a static class property

查看:37
本文介绍了实例作为静态类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 PHP 中将类的实例声明为属性?

Is it possible to declare an instance of a class as a property in PHP?

基本上我想要实现的是:

Basically what I want to achieve is:

abstract class ClassA() 
{
  static $property = new ClassB();
}

好吧,我知道我不能这样做,但是除了总是做这样的事情之外还有什么解决方法吗:

Well, I know I can't do that, but is there any workaround beside always doing something like this:

if (!isset(ClassA::$property)) ClassA::$property = new ClassB();

推荐答案

你可以使用类似单例的实现:

you can use a singleton like implementation:

<?php
class ClassA {

    private static $instance;

    public static function getInstance() {

        if (!isset(self::$instance)) {
            self::$instance = new ClassB();
        }

        return self::$instance;
    }
}
?>

然后您可以使用以下方法引用该实例:

then you can reference the instance with:

ClassA::getInstance()->someClassBMethod();

这篇关于实例作为静态类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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