The night is long!
Today I led the team to build a local website. I found that I couldn’t build it with PHP 5.2. The PHP code of the website contained many parts that were above 5.3. My boss asked me to change it so that it could run under 5.2.
I changed and found a place
self – This is this class, this class in the code segment.
static – PHP 5.3 only adds the current class, which is a bit like $this. It is extracted from the heap memory and accesses the currently instantiated class, so static represents that class.
Let’s take a look at the professional explanations from foreigners.
self refers to the same class whose method the new operation takes place in.
static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.
In the following example, B inherits both methods from A. self is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class() ).
public static function get_static() {
return new static();
}
}
class B extends A {}
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_static()); // A
I understand the principle, but the problem has not been solved yet. How to solve the problem of return new static($val);?
In fact, it is simple to use get_class($this); as follows
class B extends A {
}
$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));
/*
The result
string(1) "B"
string(1) "B"
*/