Understanding the Differences Between "New Self" and "New Static" in PHP
Converting a PHP 5.3 library to PHP 5.2 can pose challenges, primarily due to differences in syntax. One of the sticking points is the use of late static binding, such as in return new static($options).
Impact of Converting to "New Self"
Changing return new static($options) to return new self($options) will not produce the same results. Late static binding, introduced in PHP 5.3, allows you to call methods of a class using the static keyword, which refers to the class in which the method is being called. However, PHP 5.2 does not support this feature.
Key Differences Between "New Self" and "New Static"
Example:
Consider the following code:
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
In this example, the self invocation in get_self is bound to class A because the method is defined in A. However, the static invocation in get_static is bound to the class on which the method was called, which varies depending on the context (e.g., B in the second call).
Conclusion
For PHP 5.2, there is no direct workaround for late static bindings. Replacing new static with new self will not provide the same behavior. Understanding the distinction between these keywords is crucial when converting PHP 5.3 code to earlier versions.
The above is the detailed content of PHP 5.2 to 5.3 Migration: What's the Difference Between `new self()` and `new static()`?. For more information, please follow other related articles on the PHP Chinese website!