加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 22:03:32 所属栏目:PHP教程 来源:网络整理
导读:请考虑以下代码方案: ?php//widgetfactory.class.php// define a classclass WidgetFactory{ var $oink = 'moo';}??php//this is index.phpinclude_once('widgetfactory.class.php');// create a new object//before creating object make sure that it alr
请考虑以下代码方案:

<?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();
}

?>

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

解决方法

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

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

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

$WF = WidgetFactory::getInstance();

WidgetFactory的构造函数声明为protected,以确保实例只能由WidgetFactory本身创建.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读