how to check if object of a class already exists in PHP?

Go To StackoverFlow.com

3

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?

2012-04-05 21:11
by Rahul
This is a 'singleton': http://php.net/manual/en/language.oop5.patterns.php (see example #2 - Marc B 2012-04-05 21:16
http://us2.php.net/manual/en/function.class-exists.ph - j08691 2012-04-05 21:17
@j08691 I guess class_exist() wont help this case, as I want to check wheather the object exists or not and not the clas - Rahul 2012-04-05 21:20
Could be helpful http://php.net/manual/en/language.oop5.patterns.ph - The Alpha 2012-04-05 21:21
I am now looking for almost exactly the same thing. Anyone any more recent methods for achieving this - Martin 2015-12-15 15:51


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.

2012-04-05 21:18
by Linus Kleen


5

This should do the job:

if ( ($obj instanceof MyClass) != true ) {
    $obj = new MyClass();
}
2012-09-11 08:39
by Mahdi
Ads