Understanding the Distinction between new self and new static
In PHP, self and static are commonly used within class methods to instantiate new objects, particularly in the context of inheritance. However, there are subtle differences between these two keywords.
new self vs. new static
Implications for PHP 5.2
When converting a PHP 5.3 library to PHP 5.2, which lacks support for late static binding, replacing new static($options) with new self($options) may not yield the intended results. This is because self will always reference the class in which new is actually written, while static offers flexibility in target class resolution.
Example:
Consider the following code in PHP 5.2:
class A { public static function create() { return new self(); } } class B extends A {} $object = B::create(); // $object is of class A, not B
In PHP 5.3, the same code would have instantiated an object of class B because static would have resolved to the calling class.
Current Recommendations
Since PHP 5.2 is no longer actively supported, finding a workaround for this issue is not feasible. It is advisable to avoid using late static binding altogether for compatibility reasons.
The above is the detailed content of PHP `self` vs. `static`: When Does `new static()` Differ from `new self()`?. For more information, please follow other related articles on the PHP Chinese website!