New self vs. new static in PHP: Compatibility and Differences
Converting PHP 5.3 code to PHP 5.2 often presents challenges due to syntactic changes. One such challenge arises from the use of late static binding, specifically the use of return new static($options);. Replacing static with self in this context may not yield the same results.
Understanding the Difference
self refers to the class in which the new keyword is defined, while static, introduced in PHP 5.3's late static bindings feature, refers to the class in the hierarchy on which the method is invoked.
Consequences of Using new self in PHP 5.2
Replacing static with self in PHP 5.2 will result in ambiguous behavior. self will always refer to the class where the method is defined, regardless of the class where it is invoked. This can lead to incorrect object instantiation and inconsistencies.
Example
Consider the following code:
class Animal { public static function getInstance() { return new self(); } } class Dog extends Animal { public static function getInstance() { return new static(); } }
In PHP 5.3, calling Dog::getInstance() would return an instance of Dog, while calling Animal::getInstance() would return an instance of Animal.
However, in PHP 5.2, both calls would return an instance of Animal because self in both methods would refer to Animal.
Conclusion
While new self and new static are equivalent in PHP 5.3, they differ significantly in PHP 5.2. Converting new static($options) to new self($options) in PHP 5.2 may yield incorrect results, and there is no known workaround for this issue.
The above is the detailed content of PHP 5.2 vs. PHP 5.3: `new static()` vs. `new self()` – What are the Key Differences and Compatibility Issues?. For more information, please follow other related articles on the PHP Chinese website!