A class with a singleton pattern, with some questions about its static members

Source: Internet
Author: User
Tags what php
The database class for the following singleton pattern:
Class Database{static Private $db;p rivate function __construct () {}static function getinstance () {if (self:: $db) {return Self:: $db;} Else{self:: $db = new self (), return self:: $db;}}}

One argument is that a static method cannot invoke a non-static member.
So there is a sentence in the definition of this class: self:: $db = new self (); Is this self () method not a non-static constructor?
Is it inaccurate to say that static methods cannot invoke non-static members? Please advise your predecessors.


Reply to discussion (solution)

Well, it's wrong, that's the statement that instantiates the object, not the one that called the member.

Self and $this both refer to the class itself
Only the former is used in static methods, which are used in dynamic (instantiated objects) methods

New is an instantiated class, constructors cannot be static

Note that due to historical reasons, the PHP class will not be static or static, because it shuts down the e_strict level check.

Error_reporting (e_all ^ e_notice ^ e_strict); class T {  function A () {    echo ' abc ';  }} T::a ();
Abc

This is what PHP is all about.
Did you get rid of those locks and make them happy?

Self and $this both refer to the class itself
Only the former is used in static methods, which are used in dynamic (instantiated objects) methods

New is an instantiated class, constructors cannot be static

Note that due to historical reasons, the PHP class will not be static or static, because it shuts down the e_strict level check.


Yes, I get it, thanks for the answer.
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.