Function: singleton()

function singleton(string|object $interface_or_class, string $context = "default"): object;

The method singleton creates an object that supports the specified interface and ensures that only one instance of this object exists.

Details

The singleton is a usual pattern for the action objects like SessionManager, EventManager, DBWorker etc. It makes no sense to produce many instances of such classes, it wastes the computer resources and might cause errors.

Parameters

Name Pass type Value type Default value Description
$interface_or_class by value string|object

Name of the class/interface as string or the class/interface.

$context by value string "default"

The context of binding. You can introduce a different context, and bind another implementation. Then, you can request another instance specifying the context explicitly.

Returns

object

Returns object of the class bound to the interfase.

Throws

\Exception

It might throw the following exceptions in the case of any errors:

  • if the interface or class is not specified.
  • if the interface or class does not exist.
  • if the check of the classes and interfaces fails.

Authors

Oleg Schildt

Package

Source code

See also