【PHP】靜態方法呼叫非靜態方法和靜態呼叫非靜態方法程式碼解讀
阿新 • • 發佈:2018-11-20
static 關鍵字用來修飾屬性、方法,稱這些屬性、方法為靜態屬性、靜態方法。
在類的靜態方法中是不能直接以$this->test()的方式呼叫非靜態方法的。還有框架中靜態的呼叫非靜態方法是怎麼回事???
。。。
算了,不知道說啥
具體為啥看程式碼註釋:
<?php
class Pay
{
public function bike()
{
return 'I\'m going out on my bike';
}
public static function selfDriveJourney()
{
// $this->bike(); // 這個樣的寫法會直接報錯 Using $this when not in object context
// self::bike(); // self 在低版本 php 中可行,會自動將非靜態方法轉換為靜態方法,在高版本的 PHP 中會報錯 Non-static method App\\Services\\UploadFiles::saveFiles() should not be called statically
// ps:什麼?你問我PHP版本到底多高多低?我只能告訴你,我也沒測試具體版本,所以我不知道,自己去測試下吧
// 在高版本PHP中建議寫法
return (new self())->bike();
}
protected function car()
{
return 'I\'m going to drive out and play';
}
/**
* static __callStatic 靜態呼叫非靜態的方法
* @param $method
* @param $arguments
* @return mixed
*/
public function __callStatic($method, $arguments)
{
return (new static())->$method(...$arguments);
}
}
echo Pay::selfDriveJourney(); // I'm going out on my bike
echo Pay::car(); // I'm going to drive out and play
最後說明下 car 方法為啥用 protected,不用 public。官方文件有說明,public 是一個公開的可訪問方法,所以就不會走魔術方法 __callStatic 導致報錯。