Home >Backend Development >PHP Tutorial >PHP `self` vs. `static`: When Does `new static()` Differ from `new self()`?

PHP `self` vs. `static`: When Does `new static()` Differ from `new self()`?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 00:15:09522browse

PHP `self` vs. `static`: When Does `new static()` Differ from `new self()`?

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

  • self refers to the class in which the new keyword is defined, considering the current scope and inheritance hierarchy.
  • static, introduced in PHP 5.3, refers to the class on which the method invoking new was called, regardless of its inheritance hierarchy.

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!

Statement:
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