gpt4 book ai didi

php - 如何检查一个类的对象是否已经存在于 PHP 中?

转载 作者:可可西里 更新时间:2023-11-01 00:00:55 25 4
gpt4 key购买 nike

考虑以下代码场景:

<?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 本身创建。

关于php - 如何检查一个类的对象是否已经存在于 PHP 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com