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

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

Barbara Streisand
Release: 2024-12-24 01:17:10
Original
221 people have browsed it

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

When to Use 'Self' and '$This' in PHP

In PHP, understanding the distinction between 'self' and '$this' is crucial. 'Self' refers to the current class, while '$this' refers to the current object.

When to Use 'Self':

  • Accessing static members (variables or methods):

    class MyClass {
        static $static_member = 10;
    }
    echo MyClass::$static_member; // Output: 10
    Copy after login
  • Calling parent class methods:

    class ChildClass extends ParentClass {
        public function myMethod() {
            self::parentMethod(); // Calls the parent class method
        }
    }
    Copy after login

When to Use '$This':

  • Accessing non-static members:

    class MyClass {
        private $instance_member = 20;
    }
    $obj = new MyClass();
    echo $obj->instance_member; // Output: 20
    Copy after login
  • Calling instance methods:

    class MyClass {
        public function myMethod() {
            echo $this->instance_member; // Accesses the instance member
        }
    }
    Copy after login
  • Polymorphism: Calling instance methods from derived classes:

    class BaseClass {
        public function myMethod() {
            echo 'BaseClass::myMethod()';
        }
    }
    class DerivedClass extends BaseClass {
        override public function myMethod() {
            echo 'DerivedClass::myMethod()';
        }
    }
    $baseObj = new BaseClass();
    $derivedObj = new DerivedClass();
    $baseObj->myMethod(); // Output: 'BaseClass::myMethod()'
    $derivedObj->myMethod(); // Output: 'DerivedClass::myMethod()'
    Copy after login
  • Suppressing polymorphism: Calling parent class methods using 'self' in derived classes:

    class BaseClass {
        public function myMethod() {
            echo 'BaseClass::myMethod()';
        }
    }
    class DerivedClass extends BaseClass {
        override public function myMethod() {
            parent::myMethod(); // Calls the BaseClass's myMethod() using self::
        }
    }
    $derivedObj = new DerivedClass();
    $derivedObj->myMethod(); // Output: 'BaseClass::myMethod()'
    Copy after login

The above is the detailed content of PHP `self` vs. `$this`: 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