2

Consider this example singleton class:

class Model_Acl
{
    protected static $_instance;

    private function __construct($a) {
        echo $a;
    }

    public static function getInstance()
    {
        if(!isset(self::$_instance)) {
            self::$_instance = new Model_Acl('hello world');
        }
        return self::$_instance;
    }
}

In the static method of the same class, I am able to initialize the class to which constructor is private. Does that mean the scope of class initialization becomes local when trying to instantiate object within the class?

I will appreciate if someone could explain the behaviour of PHP when it comes to class instantiation with reference to access modifiers.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Ibrahim Azhar Armar
  • 24,538
  • 34
  • 126
  • 199

1 Answers1

4

You can only initialize it thru Model_Acl::getinstance().

But yes, it will work.

Singleton is not considered a good practice, you should consider Dependency Injection.

http://fabien.potencier.org/article/11/what-is-dependency-injection.

More information about php Singletons

Best practice on PHP singleton classes

Community
  • 1
  • 1
Danilo Kobold
  • 2,522
  • 1
  • 19
  • 30
  • 1
    Singletons are not considered good practice in *most* applications. They can be good though, such as for a data abstraction layer. – Adi Bradfield Jun 05 '15 at 23:12