[討論] PHP7後靜態呼叫時建立實體的方法

看板PHP作者 (夏天到了,冷不起來了說)時間3年前 (2020/06/12 08:57), 編輯推噓4(401)
留言5則, 4人參與, 3年前最新討論串1/1
以前的PHP還可以在靜態method裡使用$this,不過新版的改掉了 所以前那種 $foo = foo::bar() 等同 $foor = new foor , $foo->bar(); 的寫法在PHP7已經不可行了 class foo{ public function __construct(){ } public static function bar(){ if(!isset($this)){ $foo = new foo; return $foo->bar(); } // return blablabla.. } } 不過看laravel卻可以讓method同時被靜態呼叫又被實體呼叫 $DB = DB::table('name'); $DB = new db ; $DB->table('name'); 又是怎樣做到的呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.66.226.169 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/PHP/M.1591923430.A.E02.html

06/12 09:27, 3年前 , 1F
https://learnku.com/articles/6146 可以參考這篇看看
06/12 09:27, 1F

06/13 01:43, 3年前 , 2F
callStatic
06/13 01:43, 2F

06/14 11:13, 3年前 , 3F
return new self(...$args);
06/14 11:13, 3F

06/14 11:13, 3年前 , 4F
原來大家在靜態回傳的時候是用$this嗎 O~O!?
06/14 11:13, 4F

06/14 19:58, 3年前 , 5F
原理還是幫你new一個instance出來
06/14 19:58, 5F
文章代碼(AID): #1UujBcu2 (PHP)
文章代碼(AID): #1UujBcu2 (PHP)