2

I recently ran across a problem: object properties are recreated every time a new object is created. The flow:

  1. a new instance of Bootstrap class is created under index.php
  2. a new instance of the X class is created under Bootstrap

The point is to keep all the properties of class X by not creating a new instance of X if it has been already created once. What would be the best way to achieve this? Or maybe it is the flow itself that should be changed?

Thanks

sitilge
  • 3,687
  • 4
  • 30
  • 56
  • 2
    PHP is designed as a "run and terminate" language. If you're looking for persistence between run requests, then you need to look at session or cache or databases or memcache or redis or similar for storing data between requests.... but you really should work __with__ the "run and terminate" paradigm of PHP if you're going to be using it as a language, not try and force it to be like java or other languages where object instances exist independently or run requests – Mark Baker Mar 08 '14 at 09:42

1 Answers1

1
$x = new Bootstrap();

and somewhere in the bootstrap class:

private function instance_maker ()
{
   if($_SESSION['made_instance']=="")
   {
      //make instance
      $m = new Subclass();

      // set session to prevent further instanciation
      $_SESSION['made_instance'] = true;
   }
}
Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105