考虑下面的代码情景:如何检查一个类的对象是否已经存在于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();
}
?>
的widgetfactory类是在widgetfactoryclass.php文件,我已经包含在我的index.php文件这个文件,我的所有网站操作贯穿的index.php,即每个动作这个文件被包含,现在我只想创建widgetfactory类的对象,如果它已经不存在的话。我为此使用isset()
,有没有其他更好的替代方案?
这是一个 '单':http://php.net/manual/en/language.oop5.patterns.php(见例如#2) – 2012-04-05 21:16:50
HTTP ://us2.php.net/manual/en/function.class-exists.php – j08691 2012-04-05 21:17:24
@ j08691我想class_exist()不会帮助这种情况,因为我想检查是否存在对象而不是类 – Rahul 2012-04-05 21:20:53