php 如何在PHP中获取特定类的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2110496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:03:45  来源:igfitidea点击:

How to get instance of a specific class in PHP?

phpclassinstance

提问by user198729

I need to check if there existsan instance of class_A,and if there does exist, getthat instance.

我需要检查是否存在的实例class_A,如果存在,则获取该实例。

How to do it in PHP?

如何在 PHP 中做到这一点?

As always, I think a simple example is best.

一如既往,我认为一个简单的例子是最好的。

Nowmy problem has become:

现在我的问题变成了:

$ins = new class_A();

How to store the instance in a static member variable of class_Awhen instantiating?

如何将实例存储在实例化时的静态成员变量中class_A

It'll be better if the instance can be stored when calling __construct(). Say, it should work without limitation on how it's instantiated.

如果调用时可以存储实例就更好了__construct()。比如说,它应该不受限制地实例化它的方式。

回答by Tom Haigh

What you have described is essentially the singleton pattern. Please see this questionfor good reasons why you might not want to do this.

你所描述的本质上是单例模式。请参阅此问题,了解您可能不想这样做的充分理由。

If you really want to do it, you could implement something like this:

如果你真的想这样做,你可以实现这样的事情:

class a {
    public static $instance;
    public function __construct() {
        self::$instance = $this;
    }

    public static function get() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

$a = a::get();

回答by troelskn

What you ask for is impossible (Well, perhaps not in a technical sense, but highly impractical). It suggests that you have a deeper misunderstanding about the purpose of objects and classes.

你要求的是不可能的(好吧,也许不是技术意义上的,但非常不切实际)。它表明您对对象和类的用途有更深层次的误解。

回答by Dathan

Maybe you want something like

也许你想要类似的东西

for (get_defined_vars() as $key=>$value)
{
  if ($value instanceof class_A)
    return $value;
}

EDIT:Upon further reading, you have to jump through some hoops to get object references. So you might want return $$key;instead of return $value;. Or some other tricks to get a reference to the object.

编辑:进一步阅读后,您必须跳过一些圈子才能获得对象引用。所以你可能想要return $$key;代替return $value;. 或者其他一些获取对象引用的技巧。

回答by Pekka

if ($object instanceof class_A)

if ($object instanceof class_A)

See PHP manual: Classes and objects

参见PHP 手册:类和对象

回答by Karl B

The singleton pattern, with a PHP example from Wikipediathat I've added a "checkExists" method to, as it sounds like you want to check for the existence of the class without necessarily creating it if it doesn't exit:

单例模式,来自维基百科的一个PHP 示例,我添加了一个“checkExists”方法,因为听起来你想检查该类是否存在,如果它没有退出,则不一定要创建它:

final class Singleton 
{
    protected static $_instance;

    protected function __construct() # we don't permit an explicit call of the constructor! (like $v = new Singleton())
    { }

    protected function __clone() # we don't permit cloning the singleton (like $x = clone $v)
    { }

    public static function getInstance() 
    {
      if( self::$_instance === NULL ) {
        self::$_instance = new self();
      }
      return self::$_instance;
    }

    public static function checkExists() 
    {
      return self::$_instance;
    }
}

if(Singleton::checkExists())
   $instance = Singleton::getInstance();

回答by AntonioCS

I think what you want is the Registry Pattern

我想你想要的是注册表模式

回答by Aistina

To expand on Pikrass answer, you basically will want to do something like this:

要扩展 Pikrass 答案,您基本上需要执行以下操作:

class class_A {
  private static $instance = false;

  public static function getInstance() {
    if (!self::$instance) {
      self::$instance = new class_A();
    }

    return self::$instance;
  }

  // actual class implementation goes here
}


// where you need to use the instance:
$mySingleton = class_A::getInstance();
// do something with $mySingleton

回答by JW.

Remember that by using a singleton, you're basically creating a big global variable. If it's got state that changes, your code can become unpredictable. So use caution.

请记住,通过使用单例,您基本上是在创建一个大的全局变量。如果状态发生变化,您的代码可能变得不可预测。所以请谨慎使用。

回答by Emanuele Del Grande

If the replacement of the singleton instantiation instrucion in your files is a problem you may turn into a constant-driven behaviour: constants are such for all the duration of the script, so in case of an instance which requirement is to be unique (for all the script duration) the construction method may be properly linked to the existence/value of a constant.

如果在您的文件中替换单例实例化指令是一个问题,您可能会变成一个常量驱动的行为:常量在脚本的整个持续时间内都是这样的,所以如果一个实例的要求是唯一的(对于所有脚本持续时间)构造方法可以正确链接到常量的存在/值。

class superObject {
    public function __construct() {
        if (defined('SUPER_OBJECT')) {
            trigger_error('Super object '.__CLASS__.' already instantiated', E_USER_ERROR);
                    // ...or just do whatever you want to do in case of instances overlap
        } else {
            define('SUPER_OBJECT', true);
        }
    // the rest of your construct method
    // ...
    }
}