4

consider the following code scenario:

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

The widgetfactory class is in widgetfactoryclass.php file, I have included this file in my index.php file, all my site actions runs through index.php, i.e. for each action this file gets included, now I want to create object of widgetfactory class ONLY if already it doesn't exist. I am using isset() for this purpose, is there any other better alternative for this?

5

2 Answers 2

7

Using globals might be a way to achieve this. The common way to do this are singleton instances:

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

Then, later on, instead of checking for a global variable $WF, you can retrieve the instance like this:

$WF = WidgetFactory::getInstance(); 

The constructor of WidgetFactory is declared protected to ensure instances can only be created by WidgetFactory itself.

Sign up to request clarification or add additional context in comments.

Comments

5

This should do the job:

if ( ($obj instanceof MyClass) != true ) { $obj = new MyClass(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.