简体   繁体   English

返回对PHP中对象实例的引用

[英]Return a reference to an instance of an object in PHP

I have a singleton factory and would like it to return a reference to the object instance so that I can use the singleton factory to destroy the instance and not have instances elsewhere in my code to survive. 我有一个单例工厂,希望它返回对对象实例的引用,以便我可以使用单例工厂销毁该实例,而在我的代码中没有其他实例可以生存。

Example of what I would like to be able to do: 我想做的例子:

$cat = CatFactory::getInstance();
$cat->talk(); //echos 'meow'
CatFactory::destructInstance();
$cat->talk(); //Error: Instance no longer exists

Based on the documentation for unset , I do not think that is possible. 根据unset的文档,我认为这是不可能的。 You cannot actually destroy an object, only a handle to it. 实际上不能破坏对象,而只能破坏它的句柄。 If other variables are around that still hold a reference, the object will continue to live on. 如果周围的其他变量仍保留引用,则该对象将继续存在。

This could work: 这可以工作:

<?php
class FooFactory
{
  private static $foo;

  private function __construct()
  {
  }

  public static function getInstance()
  {
    return self::$foo ? self::$foo : (self::$foo = new FooFactory());
  }

  public static function destroyInstance()
  {
    self::$foo = null;
  }

  public function __call($fn, $args)
  {
    if (!method_exists(self::$foo, $fn) || $fn[0] == "_")
      throw new BadMethodCallException("not callable");

    call_user_func_array(array(self::$foo, $fn), $args);
  }

  # function hidden since it starts with an underscore
  private function _listen()
  {
  }

  # private function turned public by __call
  private function speak($who, $what)
  {
    echo "$who said, '$what'\n";
  }

}

$foo = FooFactory::getInstance();
$foo->speak("cat", "meow");
$foo->_listen();                 # won't work, private function
FooFactory::destroyInstance();
$foo->speak("cow", "moo");       # won't work, instance destroyed
?>

Obviously it is a hack. 显然这是一个hack。

You can accomplish what you want by having your Cat object enforce a private $destroyed property. 您可以通过使Cat对象强制执行私有的$ destroyed属性来完成所需的操作。 PHP 5 passes objects by reference by default, so you don't have to worry about that part. PHP 5默认通过引用传递对象,因此您不必担心该部分。

A work around would be creating a cat class 解决方法是创建猫类

class cat
{
  public $cat;

  public function __construct()
  {
    $this->cat = CatFactory::getInstance();
  }

  public function __destruct()
  {
    CatFactory::destructInstance();
  }

}

$cat = new cat();
$cat->cat->talk();
$cat->cat->talk();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM