


PHP 5.2 to 5.3 Migration: What's the Difference Between `new self()` and `new static()`?
Dec 18, 2024 pm 03:40 PMUnderstanding 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"
- Self: Refers to the class in which the new keyword is written.
- Static: In late static bindings (PHP 5.3 ), refers to the class on which the method was called.
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
