PHP Tutorial Tutorials - PHP OOP $this and self Keyword

PHP OOP $this and self Keyword

The pseudo-variable $this is available when a method is called from within an object context.$this is a reference to the calling object.

Let's create a House class and an object from it:

<?php
class House {
    public $color = "red";
    public function changeColor($newcolor) {
        $this -> color = $newcolor;
    }
}
$house = new House();
$house -> changeColor("blue");

We change the value of $color using changeColor() method. In the method,we use $this variable to access the current object which is calling object $house.
So it's equivalent to $house -> color = "blue".

Full test code:

<?php
// test.php
class House {
    public $color = "red";
    public function changeColor($newcolor) {
        $this -> color = $newcolor;
        var_dump($this); // object(House)#1 (1) { ["color"]=> string(4) "blue" }
    }
}
$house = new House();
echo $house -> color; //red
$house -> color = "green";
echo $house -> color; //green
$house -> changeColor("blue");
echo $house -> color; //blue
?>

Keyword self

The keyword self represent "the current class". It is always followed by the Scope Resolution Operator (::)

<?php
class House
{
    private static $owner = "Lautturi";
    
    public static function showOwner(){
        echo self::$owner;
    }
}
echo House::showOwner();
?>

Difference between self and $this

$this self
$this->property self::$property
$this->method() self::method()
Represents an object(instance of the class) Represents a class
Always begin with $ Never begin with $
followed by -> followed by ::
The property name without $ ($this->property) The property name with $ (self::$property)
Date:2019-10-09 00:40:24 From:www.Lautturi.com author:Lautturi