Home > Backend Development > PHP Tutorial > PHP 5.2 to 5.3 Migration: What's the Difference Between `new self()` and `new static()`?

PHP 5.2 to 5.3 Migration: What's the Difference Between `new self()` and `new static()`?

Barbara Streisand
Release: 2024-12-18 15:40:12
Original
649 people have browsed it

PHP 5.2 to 5.3 Migration: What's the Difference Between `new self()` and `new static()`?

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"

  • 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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template