When to use self over $this?

前端 未结 23 2815
醉梦人生
醉梦人生 2020-11-21 11:19

In PHP 5, what is the difference between using self and $this?

When is each appropriate?

23条回答
  •  梦如初夏
    2020-11-21 12:06

    Case 1: Use self can be used for class constants

     class classA { 
         const FIXED_NUMBER = 4; 
         self::POUNDS_TO_KILOGRAMS
    }
    

    If you want to call it outside of the class, use classA::POUNDS_TO_KILOGRAMS to access the constants

    Case 2: For static properties

    class classC {
         public function __construct() { 
         self::$_counter++; $this->num = self::$_counter;
       }
    }
    

提交回复
热议问题