Home > Backend Development > PHP Tutorial > How to Implement the Singleton Design Pattern in PHP5?

How to Implement the Singleton Design Pattern in PHP5?

DDD
Release: 2024-12-13 03:08:08
Original
611 people have browsed it

How to Implement the Singleton Design Pattern in PHP5?

Singleton Design Pattern in PHP5

Implementing the Singleton design pattern in PHP5 involves creating a class that can have only one instance, regardless of how many times it's instantiated. This is achieved by using a static variable to store the single instance and preventing cloning or de-serialization.

Here's an example of how to create a Singleton class in PHP5:

final class UserFactory
{
    private static $inst = null;

    // Prevent cloning and de-serializing
    private function __clone(){}
    private function __wakeup(){}

    /**
     * Call this method to get singleton
     *
     * @return UserFactory
     */
    public static function Instance()
    {
        if self::$inst === null) {
            self::$inst = new UserFactory();
        }
        return self::$inst;
    }

    /**
     * Private ctor so nobody else can instantiate it
     *
     */
    private function __construct()
    {

    }
}
Copy after login

This implementation uses a static variable $inst to store the single instance of the UserFactory class. The Instance() method serves as the singleton getter. If $inst is null, a new instance is created and assigned to $inst.

To use this Singleton class, simply call the Instance() method to obtain the single instance:

$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();
Copy after login

Comparing $fact and $fact2 will yield true, confirming that they are the same instance.

However, attempting to instantiate a new UserFactory object directly using new UserFactory() will throw an error because the constructor is made private. The only way to obtain an instance of the UserFactory class is through the Instance() method.

The above is the detailed content of How to Implement the Singleton Design Pattern in PHP5?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template