Thread: About Singleton

    #1
  1. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,672
    Rep Power
    171

    About Singleton


    Hello please answer my questions if you can thank you.

    1. I see in most scripts that use singleton, it looks like there is always a static function that calls private constructor in case it has not been instantiated yet. If it is true then how come this script works fine with no error or warnings?
      PHP Code:
      error_reporting(E_ALL);
      class 
      test_static{
          
          private static 
      $instance;
          private function 
      __construct()
              {
                  echo 
      'Connecting to database';
              }
          public function 
      connect()
              {
                  if(!
      self::$instance)
                      {
                          
      self::$instance = new test_static();
                      }
                  return 
      self::$instance
              }
      }

      test_static::connect();
      test_static::connect();
      test_static::connect();
      test_static::connect();
      test_static::connect(); 
      As you can see there are 2 problems:
      1. 1 - Function connect() is not static! Why in some documents they say the function that calls Singleton's constructor has to be static?
      2. Why is it even possible to call a non static function like
        PHP Code:
        test_static::connect(); //(Works without instantiating!!!)
        //Doesn't it have to be like 
        $object = new test_static();
        test_static->connect 






    2. Singleton is used to make sure only one instance of the class exists for the life of the current script. For example: We don't want to create a new connection every time we want to run a query.What are some other reasons to use Singleton?
    3. Is this true or false: Singleton has always got private __constructor because it must not be instantiated from out side of the class.
    4. __construct() would only be called if you called it from within a static method for the class containing the private constructor.
    5. Beside the database connections example, please give me 3 examples that Singleton is compulsory (or the best practice) .



  2. #2
  3. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    1) Because you haven't declared the class nor the constructor static, so PHP is more than happy to use your NORMAL class in the normal way. You're using it like a singleton, but it's not static.

    1.1) The docs say it must be static because otherwise you get confused.

    1.2) If a function doesn't access $this, it may be called statically as a handy favor to the programmer whether it's static or not. Dynamic functions can be called both ways. Static functions may only be called one way. It's not a mutually exclusive relationship, it's a subset.


    2) Memcache instances, global user objects, anything excessively large, session management code, and more.

    3) When written correctly, true. "Singleton" is not something in the PHP language, it's a design pattern which you must follow. Your code isn't following the pattern.

    4) See #3.

    5) See #2.
    Last edited by ManiacDan; October 14th, 2012 at 06:11 PM.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  4. #3
  5. No Profile Picture
    Banned
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    57
    Rep Power
    0
    Originally Posted by zxcvbnm
    I see in most scripts that use singleton, it looks like there is always a static function that calls private constructor in case it has not been instantiated yet. If it is true then how come this script works fine with no error or warnings?
    You're probably using an old version of PHP (< 5.4) that doesn't include strict warnings in E_ALL. Use error_reporting(-1) to make sure that you're actually getting all errors and warnings regardless of the PHP version.

    Then you should see this warning 5 times:
    Code:
    Strict Standards: Non-static method test_static::connect() should not be called statically in ... on line ...
    So this is wrong (as we already said in one of your previous threads). Even if PHP didn't complain at all, that wouldn't make it right. It would simply mean that the error system doesn't work.

    Just don't do this. Calling non-static methods in a static way is always wrong, even if it doesn't always always cause an error message in PHP.



    Originally Posted by zxcvbnm
    1 - Function connect() is not static! Why in some documents they say the function that calls Singleton's constructor has to be static?
    Because that's the only way to make the singleton pattern work. Just think about it: If the singleton's factory method (don't confuse it with the constructor) wasn't static, then you would need to instantiate the class before you could instantiate it. That obviously doesn't make sense.

    In your case the code only works because PHP corrects your mistakes. It calls the connect() method in a static way even if it's not declared as static. This wouldn't work in other languages.



    Originally Posted by zxcvbnm
    Why is it even possible to call a non static function like
    PHP Code:
    test_static::connect(); //(Works without instantiating!!!)
    //Doesn't it have to be like 
    $object = new test_static();
    test_static->connect 
    No, in this case the connect() method must actually be declared as static.

    It works because PHP lets you do all kinds of nonsense without complaining much.



    Originally Posted by zxcvbnm
    Singleton is used to make sure only one instance of the class exists for the life of the current script. For example: We don't want to create a new connection every time we want to run a query.What are some other reasons to use Singleton?
    A configuration file, an object representing the current user -- anything that only makes sense as a unique object.




    Originally Posted by zxcvbnm
    Is this true or false: Singleton has always got private __constructor because it must not be instantiated from out side of the class.
    Well, this is the usual way to implement a singleton. Of course, you could also make the constructor public and let it throw an exception when it's called more than once. But that's obviously very confusing.

    The clean way is to have a static factory method and restrict direct access to the constructor.







    Originally Posted by zxcvbnm
    __construct() would only be called if you called it from within a static method for the class containing the private constructor.
    Already answered above. How do you want to call a non-static method before you even have an instance?



    Originally Posted by zxcvbnm
    Beside the database connections example, please give me 3 examples that Singleton is compulsory (or the best practice) .
    Is this homework?
  6. #4
  7. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,672
    Rep Power
    171
    Originally Posted by ManiacDan
    1) Because you haven't declared the class nor the constructor static.
    Declared the class static? I understand to how declare properties or methods static, but how can I declare a class static? We obviously can't say class static test_static. I wonder what you mean by that.

    About Constructor , I wasn't sure if it is neccessary to make is static. I am studying Northie's DB class and I believe he is using Singleton design pattern.
    Originally Posted by ManiacDan
    "Singleton" is not something in the PHP language, it's a design pattern which you must follow. Your code isn't following the pattern.
    I wonder why you say that. I originally got the idea from Tony Marston's website. . I had another go with this code I wrote and it works ok:
    PHP Code:
    class test_static2{
        private static 
    $instance;
        private function 
    __construct()
            {
                echo 
    "\n**Instantiated**\n";
            }
        public static function 
    connect()
            {
                if(!
    is_object(self::$instance))
                    {
                        
    self::$instance= new test_static2();
                    }
                else
                    {
                        echo 
    "\n..Do not need to re-instantiate..\n";
                    }
                           return 
    self::$instance;
            }    
    }
    /*Prints:
    **Instantiated**

    ..Do not need to re-instantiate..

    ..Do not need to re-instantiate..

    ..Do not need to re-instantiate..*/ 
  8. #5
  9. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,672
    Rep Power
    171
    Originally Posted by Jacques3
    In your case the code only works because PHP corrects your mistakes.
    I wish it wouldn't work and instead showed me an error.

    Thank you.
  10. #6
  11. A Change of Season
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    2,672
    Rep Power
    171
    @ManiacDan; I liked your post. I have a few things I like to mention.

    First on OOP =>I have never seen teachers or students struggling this much on a subject in any field.

    I believe its for 2 mistakes most teachers (not Devshed helpers)make when teaching OOP:
    1. Most teachers sub-consciously assume the student already knows "it" and "it" could be lot of things! Just because I know "it" and "it" has already made sense to me, doesn't mean the student knows it too!
    2. The most important thing before teaching a subject is presenting "Whys" and "The reasons why this topis is important". I am currently doing PHP II higher structures in zend.com. The teachers lack of ability to explain the purpose of concepts in OOP is shocking. She keeps saying, wait for it to grasp and she keeps reading the manual. Requix was telling me sometimes how it is not even necessary to write a class for somethings.

    They may look pretty basic but they are extremely important elements of teaching.

    On top of that look at the options! When I speak to experts I get very different things lol. PHP? Ruby, Python,,,, and same with php itself, Zend is not good, cake is better, symfony is better, o no wait, you wanna learn OOP, start with JS! Could be a bit misleading.

    Its nobody's fault this process is not very simple. I believe one must pick 1 thing, stick to it and just go for the ride. There was a point I learned the hard way that dude! Pick a frame work, learn oop otherwise you cant get where you want to get.

    I am not desperate for this at this stage - which is great, gives me peace of mind - but I made the deal with myself. I must learn OOP and Zend Framework up to a very good level and I do not care what it takes to do it. Thankfully I don't have serious $ issue and I can spend a good 2 hours daily on this. I am going through these basics for now and hopefully I do a Zend Frame work fundamentals course in December.



    Thanks for your support and while I got you here, about Singleton, does post #4 make sense to you?

    Cheers

    ===============================
    **Edit:
    I also noticed there are few ways to do this, which one is preferred?
    PHP Code:
    if(!is_object(self::$instance))
        {
            
    self::$instance= new Database();
        }
    /////////////
     
    if (!self::$m_instance)
            {
                    
    self::$instance= new Database();
            } 
    ////////////
    /////////////
    if(is_null(self::$instance))
            {
                    
    self::$instance= new Database();
            } 
    //////////// 
    Last edited by zxcvbnm; October 14th, 2012 at 08:57 PM.
  12. #7
  13. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    The "it" and the "why" of OOP are unfortunately very high level. you can't demonstrate them with very small examples. It serves you no benefit at all to make a very small class in any language, especially not one with all the small classes like ArrayObject already done for you like PHP. Maybe in C++ a tuple class or a list object class could show you right away how useful it could be, but the data structures are already done in PHP.

    If you really want to learn, you can LOOK at the pre-written solutions like cake and symfony, but only as examples. They have their own strengths and weaknesses. Cake isn't well separated. Symfony has 7 classes for every database table, and it's nearly impossible to figure out what's going on if you're new.

    The basic reason to use objects is: You have a lot of similar functionality that shares a theme, and even shares some variables, and you want all of that contained in a package so you can just use the package without worrying about which functions go where and whether the variables are set. So you put it in a class. That's the first step, that's what gets you a database class, and then a user class. Once you're comfortable with that level of access, you can think about controllers and routers and templating engine classes. Until then, use classes within your existing code, transferring things into classes when you think it's necessary. I write nothing but OOP code for work, and pretty much nothing but procedural code for the forums and personal scripts. It's just faster to develop a one-time script without using objects.

    The real benefit of objects is in long-term development, maintainability, and understandability. You will kill yourself trying to maintain 100,000 lines of procedural code, regardless of the language. Object oriented code is more modular, things are contained, so you don't have to see all the innards of all the functions all at once. It's much easier to understand "a car" than to understand the entire blueprints of the machine and how it relates to the road and to the passengers.

    As for your question at the end: All of them accomplish the same purpose. In PHP with loose typing (== as opposed to ===), something which is not set is equal to null and to false, and that thing is not an object. All three lines are the same (though some may throw warnings). Since this variable is only accessible from inside a single function on the class, it doesn't really matter which you pick, it's a style thing. I believe !self::something is the fastest method, but speed really isn't your concern for stuff like that.
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.
  14. #8
  15. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,317
    Rep Power
    7170
    Its nobody's fault this process is not very simple. I believe one must pick 1 thing, stick to it and just go for the ride. There was a point I learned the hard way that dude! Pick a frame work, learn oop otherwise you cant get where you want to get.
    This is a good approach. You could spend a lifetime trying to find the perfect way to program everything, and you would never find it. Sometimes you just have to accept a design that works even if it is less than perfect. If you don't, you will never finish anything. That's a lesson I'm still trying to learn.
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  16. #9
  17. Confused badger
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Mar 2009
    Location
    West Yorkshire
    Posts
    1,112
    Rep Power
    487
    Hey guys just wanted to chip in as the things that zxcvbnm are doing now are along the same lines as me so the threads (s)he's been posting recently have been really helpful so PLEASE can we stop turning this into a p**sing war of if PHP is the 'best' or the 'right' language they should be using?

    It's nice there's an interesting and very high level debate about it but please can you keep it to your personal inboxes or "that" other thread (yes, we all know which one I mean!)
    "For if leisure and security were enjoyed by all alike, the great mass of human beings who are normally stupefied by poverty would become literate and would learn to think for themselves; and when once they had done this, they would sooner or later realise that the privileged minority had no function and they would sweep it away"
    - George Orwell, 1984
  18. #10
  19. Sarcky
    Devshed Supreme Being (6500+ posts)

    Join Date
    Oct 2006
    Location
    Pennsylvania, USA
    Posts
    10,908
    Rep Power
    6351
    The most common ridiculous PHP argument has been split into its own thread. Most of the forum is happy to answer your PHP questions without turning it into a critique of the language in general or a recommendation to stop learning PHP.

    Comments on this post

    • badger_fruit agrees : Hahaha, love it "Yet another argument with Jacques about whether PHP is worthwhile"
    HEY! YOU! Read the New User Guide and Forum Rules

    "They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety." -Benjamin Franklin

    "The greatest tragedy of this changing society is that people who never knew what it was like before will simply assume that this is the way things are supposed to be." -2600 Magazine, Fall 2002

    Think we're being rude? Maybe you asked a bad question or you're a Help Vampire. Trying to argue intelligently? Please read this.

IMN logo majestic logo threadwatch logo seochat tools logo