-
-
Save masiur/018d031e390ab12f130a03803b4a3af7 to your computer and use it in GitHub Desktop.
What is the difference between new self and new static?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* What is the difference between new self and new static? | |
* self refers to the same class in which the new keyword is actually written. | |
* | |
* static, in PHP 5.3's late static bindings, | |
* refers to whatever class in the hierarchy you called the method on. | |
* | |
* In the following example, B inherits both methods from A. | |
* The self invocation 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()); // A | |
echo get_class(B::get_static()); // B | |
echo get_class(A::get_self()); // A | |
echo get_class(A::get_static()); // A |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment