Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 452
Rahul Avatar asked Dec 16 '22 01:12

Rahul


1 Answers

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.

like image 152
Linus Kleen Avatar answered Jan 05 '23 19:01

Linus Kleen