Long night!
Today, leaders build a local site. It was found that PHP 5.2 could not be built, and the website PHP Code contains more than 5.3 of the content. The leaders forced me to run the changes under 5.2.
Changed and found a place
return new static($val);
This Nima is a magic horse. I have seen it before.
return new self($val);
So I checked the difference between them online.
Self-is the class in the code snippet.
Static-PHP 5.3 only adds the current class, which is a bit like $ this. It is extracted from the heap memory and accessed by the class currently instantiated, static indicates the class.
Let's take a look at the professional explanations of foreigners.
self
Refers to the same class whose methodnew
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 fromA
.self
Is boundA
Because it's defined inA
'S implementation of the first method, whereasstatic
Is bound to the called class (also seeget_called_class()
).
class A { public static function get_self() { return new self(); } public static function get_static() { return new static(); }}class B extends A {}echo get_class(B::get_self()); // Aecho get_class(B::get_static()); // Becho get_class(A::get_static()); // A
You can understand this example.
I understand the principle, but the problem has not been solved. How can I solve the return new static ($ Val) problem?
In fact, it is simple to use.Get_class ($ this); as follows
class A { public function create1() { $class = get_class($this);
return new $class(); } public function create2() { return new static(); }}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"*/