Kaedah Statik dan $this dalam OOP dalam PHP

Di dalam kaedah statik, $this tidak boleh diakses. Ini berlaku kerana kaedah statik boleh dipanggil di luar konteks objek, hanya dengan merujuk kepada nama kelas.

Dalam kaedah biasa, kedua-dua sifat dan kaedah statik dan biasa boleh diakses.

Mari kita lihat contohnya. Contoh untuk kaedah biasa:

Test.php<?php
  class Test
  {
    public static $staticProperty = 'static';
    public $usualProperty = 'usual';
    
    public function method()
    {
      echo self::$staticProperty; // akan memaparkan 'static'
      echo $this->usualProperty;  // akan memaparkan 'usual'
    }
  }
  
  $test = new Test;
  $test->method();
?>

Contoh untuk kaedah statik:

Test.php<?php
  class Test
  {
    public static $staticProperty = 'static';
    public $usualProperty = 'usual';
    
    public static function method()
    {
      echo self::$staticProperty; // akan memaparkan 'static'
      echo $this->usualProperty;  // akan memberikan ralat
    }
  }
  
  $test = new Test;
  $test::method();
?>