เมธอดแบบสแตติกและ $this ใน OOP ใน PHP

ภายในเมธอดแบบสแตติกไม่สามารถเข้าถึง $this ได้ สิ่งนี้เกิดขึ้นเนื่องจากเมธอดแบบสแตติก สามารถถูกเรียกใช้ได้นอกบริบทของอ็อบเจ็กต์ เพียงแค่อ้างถึงชื่อคลาส

ในเมธอดธรรมดาสามารถเข้าถึงทั้งคุณสมบัติและเมธอด แบบสแตติกและแบบธรรมดาได้

มาดูตัวอย่างกัน ตัวอย่างเมธอดธรรมดา:

Test.php<?php
  class Test
  {
    public static $staticProperty = 'static';
    public $usualProperty = 'usual';
    
    public function method()
    {
      echo self::$staticProperty; // จะแสดง 'static'
      echo $this->usualProperty;  // จะแสดง 'usual'
    }
  }
  
  $test = new Test;
  $test->method();
?>

ตัวอย่างเมธอดแบบสแตติก:

Test.php<?php
  class Test
  {
    public static $staticProperty = 'static';
    public $usualProperty = 'usual';
    
    public static function method()
    {
      echo self::$staticProperty; // จะแสดง 'static'
      echo $this->usualProperty;  // จะให้ข้อผิดพลาด
    }
  }
  
  $test = new Test;
  $test::method();
?>