So I'm using some OOP on a big project, I sometimes find myself using self:: and static vars. I read some stuff about singletons and that they rock and also have downsides. Anyway, I don't want to be using singletons all over the place, but I do use some static and self:: methods in some classes.

But, does using self and static automatically make the class a singleton..?

    No.

    A singleton means that you can only ever have one instance of the object. This is good for things like database connections where you want to make sure that you don't try and connect to that database more than once.

    You do however need to use static methods to make a singleton in the usual fashion.

    I blog a bit and in my first post I was building myself up to write about something more interesting... So I wrote about Singletons as a easy start. You can find an example and a bit of info about them here; http://blog.dougalmatthews.com/2008/04/design-patterns-the-singleton/

    Singletons do get some bad comments about them because some people use them when they are lazy and basically replace global vars with singletons. Overuse of them can make code harder to read etc. but as you said, you don't want to put them all over the place, so thats good 😉

      I often not instantiate a class at all, but do set the constructor to private. Then by using self:: (which I believe obligates me to use static vars as well) I can fill the class with information I then can get from anywhere through class::method or class::$attribute.

      since it's not instantiated at all, that means by definition it's not a singleton?

        I think so, a singleton in its strictest sense is a single instance of an object. However, there are probably variations to this definition.

        You sound like you are creating something similar however.

        Basically a singleton would set the constructor to private, then a static method would make a new instance since it's inside the class and can access the private constructor. It would store this instance and return it each time the method is called.

        do say you do;
        MyClass::getInstance()

        First time it would create an instance and return it, from then on it would just return the same instance. The advantage this has over your method is it allows you then to use the object like normal once you have it and not rely on so many static methods.

          Write a Reply...