Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

Understanding when we chose `self` or `this` for access class members in PHP

`self` and `this` Keyword inside a Class

We use `self` keyword to access static class members and use `$this` for non-static members

              
                class Car
                {
                  /**
                  * $brake number;
                  *
                  */
                  public static $brake;

                  /**
                  * $speed number;
                  *
                  */
                  public $speed;

                  public static function braking($brake) {
                    self::brake = $brake;
                    return $this->speed - $brake;
                  }
                }
              
            

`self` and `this` keyword on inherited object

In this example, self::who() will always output ‘parent’, while $this->who() will depend on what class the object has.
Now we can see that self refers to the class in which it is called, while $this refers to the class of the current object.

              
                class ParentClass {
                	function test() {
                		self::who();	// will output 'parent'
                		$this->who();	// will output 'child'
                	}

                	function who() {
                		echo 'parent';
                	}
                }

                class ChildClass extends ParentClass {
                	function who() {
                		echo 'child';
                	}
                }

                $obj = new ChildClass();
                $obj->test();