If by now I understood a little in ststic Now I realize I do not understand anything. I'm so confused and I struggle to understand and I can not. Someone can explain this program when using self, parent, static and how All the smallest change I do changes the result without that I can not understand what's going on. thanks a lot ..
the code from http://docs.php.net/language.oop5.late-static-bindings
<?php
class A {
public static function foo() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
class B extends A {
public static function test() {
A::foo();
parent::foo();
self::foo();
}
public static function who() {
echo __CLASS__."\n";
}
}
class C extends B {
public static function who() {
echo __CLASS__."\n";
}
}
C::test();
?>
The out put are:
A
C
C
The key to the answer is static::who(), remember static:: means you call the method with the actual class (in our case - C).
so C::test() run as follows:
if instead of static::who() foo was calling self::who() you would have get three A as a result.
Look at http://php.net/manual/en/language.oop5.static.php. It says:
You cannot use
$this
because when calling a static method, there is no instantiated class object to be placed in the$this
variable. So you useself::
.parent::
is referring to the parent class that the current class is extending. For example, for Class C the parent class is Class B, and for Class B, the parent class is Class A. See http://php.net/manual/en/keyword.parent.php.You use static methods when you want the function to be accessible without actually having an instance of that class declared.
Upon closer inspection of your question, your link points to Late Static Bindings. The first two examples in that page pretty clearly indicate the need for the
static::
syntax, but to clarify for the example you posted:Take a look at the
foo()
method in Class A. It callsstatic::who()
. This means that the methodwho()
will be called in the scope of the class that called the function, instead of the scope of the class where the function is defined. So if you were to callC::foo()
, it would echo C.If, instead, it called
self::who()
, it would be callingA::who()
. Because within Class A,self::
refers to A.Hopefully that helps.
You'll need to understand the concept of Late Static Binding, which determines when an identifier is bound to code/data. You can tell PHP to bind it early (
self::
) or later (static::
).Slimming the example down to two classes we get: