This article mainly introduces the similarities and differences between newstatic () and newself () in PHP, which is a very practical technique, for more information about the differences between new static () and new self () in PHP, I believe it will help you to learn PHP programming.
The cause of the problem is to build a local site. It is found that PHP 5.2 cannot be set up. The website PHP code contains more than 5.3 parts and requires that the changes be executed 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 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. 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 ()).
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 also simple to use get_class ($ this); the code is 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"*/
If you are interested, you can test the sample code. I believe there will be new gains!