This article mainly introduces the differences between newstatic () and newself () in PHP. if you need them, you can refer to the 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
The code is as follows:
Return new static ($ val );
This Nima is a magic horse. I have seen it before.
The code is as follows:
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 ()).
The code is as follows:
Class {
Public static function get_self (){
Return new self ();
}
Public static function get_static (){
Return new static ();
}
}
Class B extends {}
Echo get_class (B: get_self (); //
Echo get_class (B: get_static (); // B
Echo get_class (A: get_static (); //
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); as follows:
The code is as follows:
Class {
Public function create1 (){
$ Class = get_class ($ this );
Return new $ class ();
}
Public function create2 (){
Return new static ();
}
}
Class B extends {
}
$ B = new B ();
Var_dump (get_class ($ B-> create1 (), get_class ($ B-> create2 ()));
/*
The result
String (1) "B"
String (1) "B"
*/