Use an instance of an object throughout the site using PHP

How can I use an instance of an object that is initially uploaded throughout the site?

I want $ myinstance to be used everywhere.

$myinstance = new TestClass();

Thank!

+3
source share
4 answers

What you are looking for is called a singleton pattern.

If you are deeply involved in OOP architecture and want to do things like Unit Testing: Singletons in the future are seen as an imperfect approach, not a “clean” one in the sense of OOP. I asked a question about the problem once and got good results with other, better templates. Lots of good reading.

-, DB , Singleton.

+6

(, ), , "global". . http://php.net/global.

0

100%, , ... .

, , serialize/unserialize / . , TestClass , , .

:

if (!isset($_SESSION["my_class_session_var"])) // The user is visiting for the 1st time
       {
       $test = new TestClass();
       // Do whatever you need to initialise $test...
       $_SESSION["my_class_session_var"] = serialize($test);
       }
 else   // Session variable already set. Retrieve it
       {
       $test = unserialize($_SESSION['my_class_session_var']);
       }
0

, Singleton. :

Change __construct and __clone to private, so calling the new TestClass () will fail!

Now create a class that will create a new instance of your object or return an existing one ...

Example:

abstract class Singleton
{
  final private function __construct()
  {
    if(isset(static::$instance)) {
      throw new Exception(get_called_class()." already exists.");
    }
  }

  final private function __clone()
  {
    throw new Exception(get_called_class()." cannot be cloned.");
  }

  final public static function instance()
  {
    return isset(static::$instance) ? static::$instance : static::$instance = new static;
  }
}

Then try extending this class and defining a static instance variable $

class TestClass extends Singleton
{
  static protected $instance;


  // ... 
}

Now try the following:

echo get_class($myinstance = TestClass::instance();
echo get_class($mysecondinstance = TestClass::instance());

Done

0
source

Source: https://habr.com/ru/post/1743230/


All Articles