如何检查PHP中的对象是否已经存在?

Rah*_*hul 3 php

请考虑以下代码方案:

<?php

//widgetfactory.class.php
// define a class
class WidgetFactory
{
  var $oink = 'moo';
}

?>


<?php

//this is index.php
include_once('widgetfactory.class.php');

// create a new object
//before creating object make sure that it already doesn't exist

if(!isset($WF))
{
$WF = new WidgetFactory();
}

?>
Run Code Online (Sandbox Code Playgroud)

widgetfactory类在widgetfactoryclass.php文件中,我已将此文件包含在我的index.php文件中,我的所有站点操作都通过index.php运行,即对于此文件包含的每个操作,现在我想创建widgetfactory类的对象只要它已经不存在了.我正在isset()为此目的使用,还有其他更好的选择吗?

Lin*_*een 7

使用全局变量可能是实现此目的的一种方法.执行此操作的常见方法是单例实例:

class WidgetFactory {
   private static $instance = NULL;

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

   /*
    * Protected CTOR
    */
   protected function __construct()
   {
   }
}
Run Code Online (Sandbox Code Playgroud)

然后,稍后$WF,您可以检索实例,而不是检查全局变量:

$WF = WidgetFactory::getInstance();
Run Code Online (Sandbox Code Playgroud)

WidgetFactory声明构造函数protected以确保实例只能由其WidgetFactory自身创建.


Mah*_*hdi 5

这应该做的工作:

if ( ($obj instanceof MyClass) != true ) {
    $obj = new MyClass();
}
Run Code Online (Sandbox Code Playgroud)