Difference between new self () and new static () in PHP object-oriented analysis, selfstatic
Preface
This article mainly introduces the differences between new self () and new static () in PHP object-oriented methods. What are the differences between the new methods and objects, to put it bluntly, is the new instance of the same class or different class? I won't talk much about it below. Let's take a look at the detailed introduction.
The differences are as follows:
First, clarify the conclusion. In PHP, self points to the class that defines the currently called method, and static points to the class that calls the current static method.
Next, we will use an example to prove the above results.
Class A {public static $ _ a = 'class a'; public static function echoProperty () {echo self: $ _. PHP_EOL;} class B extends A {public static $ _ a = 'class B ';} $ obj = new B (); B: echoProperty (); // output Class
The reason for this is that the use of self: Or _ CLASS _ for static reference to the current CLASS depends on the CLASS that defines the method to be called, change the echoProperty of the Class A method above:
Class A {public static $ _ a = 'class a'; public static function echoProperty () {echo static ::$ _. PHP_EOL ;}// call B: echoProperty again to output 'class B'
To avoid the subclass seen in the first example from overwriting the static attribute of the parent class, PHP5.3 adds a new syntax: later static binding uses the static keyword instead of the self keyword, so that static points to the same class returned by get_called_class (), that is, the class that currently calls the static method, this keyword is also valid for access to static methods.
The following example better illustrates the difference between new self () and new static () (the latter uses PHP's later static binding to point to the current class of the call method)
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_self()); // Aecho get_class(A::get_static()); // A
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.