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?

Rahul
  • 2,189
  • 7
  • 40
  • 60

2 Answers2

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.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
5

This should do the job:

if ( ($obj instanceof MyClass) != true ) {
    $obj = new MyClass();
}
Mahdi
  • 9,247
  • 9
  • 53
  • 74