0

This is the project I am reading from . https://github.com/sasatomislav/PHP5-OOP-Cart

class Cart 
{
	
<snip>
private function __construct() {}
	
	/**
	 * Fetch Cart instance
	 *
	 * @return Cart
	 */
    public  function getInstance()
    {
        if (NULL === self::$_instance) {
            self::$_instance = new self;
        }
        
        return self::$_instance;
    }
}
<snip>

// initialize shopping cart
// note that Cart implements Singleton pattern
$cart = Cart::getInstance();

How is getInstance which is not a static method, called using :: .

the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

getInstance is neither static or constant or being overriden here..
Further if I make getInstance static, it makes noe difference to the code.

Confused. Explain please.

4
Contributors
8
Replies
9
Views
5 Years
Discussion Span
Last Post by pritaeas
0

This a singleton. Ensuring that only one instance can exist. You don't want more than one instance of it.

0

Thanks, googling singleton explains things, but still how can :: call a non-static method ?

0

are you sure its related to late static bindings ? There is no inheritance going on in the above example. plus in the example 3 you mentioned :

class A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

scope resolution operator is called by the static keyword , and not with a classname.

0

Crap, wrong url... Now to find it again...

Anyway, the scope resolution can be used with self, parent and static, but since 5.3.0 also with a classname in a variable. From the manual: "...the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class." My guess is that since PHP is not as strict as your average language, some requirements are a little flexible. Perhaps if you run it with E_STRICT that you get a warning.

Edited by pritaeas: n/a

2

That you can do something with a language doesn’t mean that you should. From PHP4 some programmers used techniques that were against any object oriented logic, of course PHP changed and then they had problem maintaining their code. This is also the case here, it is a rather old bug, see the page bellow…
https://bugs.php.net/bug.php?id=44944

Votes + Comments
Lucky guess on my side then...
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.