---
description: Hecchi hackmd abc
---
# PHP - $this, self, static 差異
###### tags: `PHP` `Coding Tips` `OOP`
{%hackmd theme-dark %}
稍微試 run 一下範例
```php=
<?php
class ParentClass
{
public function test()
{
self::who();
$this->who();
}
public function who() {
echo 'parent'.PHP_EOL;
}
}
class ChildClass extends ParentClass
{
public function who()
{
echo 'child';
}
}
$obj = new ChildClass();
$obj->test();
// parent
// output
```
從上面的範例我們可以知道 `self` 指向的是當前呼叫的 `class`,也就是 `ParentClass` 本身,所以它最後 call 的是 `ParentClass` 底下的 `who` 這個 function。因此 output 是 **parent**。
而 `$this` 之所以會輸出 **child**,是因為 `$this` 是指向當前 call 這個 function 的 object,換句話說 `$this` 指向的其實是 `$obj` 這個 object,而 `$obj` 的 class 是 `ChildClass` ,所以 `$this` 指向了 `ChildClass` 底下的 `who` 這個 function。
那 `self` 與 `static` 之間的 call 又有什麼不同呢?差別在於「指向的 class」,具體的差異可以看以下的範例:
```php=
<?php
class ParentClass
{
const constant = 'const_parent';
public function showConst()
{
echo self::constant;
echo PHP_EOL;
echo static::constant;
}
}
class ChildClass extends ParentClass
{
const constant = 'const_child';
}
$child = new ChildClass();
$child->showConst();
// const_parent
// const_child
```
從上面的範例,我們可以看到 `self` 呼叫的是 `ParentClass` 下的 `constant`,而 `static` 呼叫的則是 `ChildClass` 下的 `constant`。之所以會出現這樣的差異的原因,是因為「兩邊所指向的 class 不同」所造成的。
`self` 所指向的 class 是當前這個被 call 的 function 的 class,而在這 class 下 `self` 會取得當前這個 class 下的 constant,而 `static` 指向的是向下 call 這個 function 的原本的 class,也就是 `ChildClass`,因此`static` 取得的 `constant` 才會是 const_child。
## 總結
`$this`:指向的是當前的 object 的 class。
`self`:指向的是當前的 class。
`static`:指向的是原來 call function 的 class。
## Reference
[Scope Resolution Operator (::)](https://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php)