Home > Backend Development > PHP Tutorial > PHP 5: `$this` vs. `self` – When to Use Each?

PHP 5: `$this` vs. `self` – When to Use Each?

Patricia Arquette
Release: 2024-12-20 06:34:10
Original
648 people have browsed it

PHP 5: `$this` vs. `self` – When to Use Each?

Self vs. $this: When and How to Use Each

Question:

In PHP 5, how do the keywords "self" and "$this" differ in their usage? When should each be used appropriately?

Answer:

Short Answer:

Use "$this" to refer to the current object's instance variables and methods. Use "self" to refer to the current class's static variables and methods.

Full Answer:

Non-Static vs. Static Members:

  • "$this->member" accesses non-static member variables and methods specific to the current object.
  • "self::$member" accesses static member variables and methods shared by all instances of the class.

Polymorphism:

  • "$this" can demonstrate polymorphism by calling methods defined in derived classes.
  • "self" suppresses polymorphism and always calls the method defined in the current class.

Example (correct usage):

class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo $this->non_static_member . ' ' . self::$static_member;
    }
}

new X(); // Output: 1 2
Copy after login

Example (incorrect usage):

class X {
    private $non_static_member = 1;
    private static $static_member = 2;

    function __construct() {
        echo self::$non_static_member . ' ' . $this->static_member; // Incorrect usage
    }
}

new X(); // Error: Undefined properties
Copy after login

Suppressing Polymorphism:

class X {
    function foo() {
        echo 'X::foo()';
    }

    function bar() {
        self::foo(); // Suppresses polymorphism
    }
}

class Y extends X {
    function foo() {
        echo 'Y::foo()';
    }
}

$x = new Y();
$x->bar(); // Output: X::foo()
Copy after login

Summary:

Use "$this" for non-static member access and polymorphism. Use "self" for static member access and when you need to suppress polymorphism.

The above is the detailed content of PHP 5: `$this` vs. `self` – When to Use Each?. 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