How to check if a class object already exists in PHP?

consider the following code script:

<?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 the widgetfactoryclass.php file, I have included this file in my index.php file, all the actions of my site are done through index.php, that is, for each action that this file is bundled with, now I want to create an object of the widgetfactory class ONLY if it doesn't already exist. I am using isset()

for this purpose, is there any other better alternative for this?

+3


source to share


2 answers


Using globals can be a way to achieve this. The general way to do this is single 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 and then instead of checking the global variable, $WF

you can get an instance like this:



$WF = WidgetFactory::getInstance();

      

A constructor is WidgetFactory

declared protected

to make sure that instances can only be created WidgetFactory

.

+7


source


This should do the job:



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

      

+5


source







All Articles