Re: [請益] Method直接用Static呼叫的問題
我先假設 PHP 對 static 的定義跟 Java 完全一樣
(版主可以因此直接砍掉這篇,我不會有怨言的 [逃])
※ 引述《tails32100 (Tails)》之銘言:
: 小弟這問題一年前就有了
: 原文:
: https://disp.cc/b/tails#!546-3zvE
: 剛剛把程式碼再拿出來試
: 發現出現錯誤
: Strict standards: Non-static method A::testA() should not be called statically
: , assuming $this from incompatible context in BALABALA
: 然後上網google一下錯誤,這好像是error_reporting的等級有包括E_STRICT
: 可是好像網路有些framework都有用到這個寫法 (CakePHP、XOOPS)
: 小弟的問題是:
: 這個寫法是建議不要用,還是可以用?
static 的 method 要用不 static 的方法呼叫
這不太好,但通常會被接受
非 static 的 method 用 static 的方法呼叫
喵的,PHP 還能讓你執行真是有點莫名其妙 [無誤]
還是看一下 [php.net] 對 static 的解說
[php.net]: http://php.net/manual/en/language.oop5.static.php
Declaring class properties or methods as static
makes them accessible without needing an instantiation of the class.
A property declared as static can not be accessed with an
instantiated class object (though a static method can).
用擬人化一點的講法,以 static 修飾的東西(method/field 均可)
他是超然「物」外的(謎之聲:X你X的完全沒有比較好懂 [毆])
他跟你有沒有 new 出那個 instance 沒有關係
你就算是 new 出 100 個 instance
那個 static 修飾的東西還是只有一個
當然,不可否認的,這樣子惡搞很多時候很好用 [遮臉]
//也許不能這樣用,我沒有實際測試過 [逃]
class Foo {
private static $counter = 0;
private $id;
public function Foo() {
Foo::$counter++;
$this->id = Foo::$counter;
}
public funtion getId() { return $this->id; }
}
但這樣的惡搞,其實還是凸顯了 $counter 超然於 Foo 以外
你可以想成,$counter 放在 Foo 底下只是為了方便呼叫 & 管理而已
所以在 static 的 method 當中,因為根本沒有 instance
所以也就根本不可能知道什麼叫驚喜... 我是說 $this
如果能讓我大放厥詞的話
我會說(過去某版?)PHP 炸 error 的點太奇怪了
怎麼會用 static 的方式叫用非 static 的 method 還可以過
噴的 error 反而是 $this 找不到.......
(沒用到 $this 的人就會一直以為這樣可以用.... [抖])
====
然後剛剛看報紙 (X) php.net (O) 才知道
PHP 的 static field,限制還蠻大的...... Orz
果然我的智商低到只能乖乖寫 Java 嗎? [淚目]
--
錢鍾書: 說出來的話
http://www.psmonkey.org
比不上不說出來的話
Java 版 cookcomic 版
只影射著說不出來的話
and more......
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.25.5.37
推
07/18 11:02, , 1F
07/18 11:02, 1F
→
07/18 11:04, , 2F
07/18 11:04, 2F
→
07/18 11:04, , 3F
07/18 11:04, 3F
→
07/18 11:05, , 4F
07/18 11:05, 4F
→
07/18 11:06, , 5F
07/18 11:06, 5F
推
07/18 11:38, , 6F
07/18 11:38, 6F
→
07/18 11:40, , 7F
07/18 11:40, 7F
→
07/18 11:40, , 8F
07/18 11:40, 8F
→
07/18 11:42, , 9F
07/18 11:42, 9F
推
07/18 11:52, , 10F
07/18 11:52, 10F
→
07/18 15:54, , 11F
07/18 15:54, 11F
→
07/18 15:55, , 12F
07/18 15:55, 12F
推
07/18 18:14, , 13F
07/18 18:14, 13F
→
07/18 18:14, , 14F
07/18 18:14, 14F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
PHP 近期熱門文章
PTT數位生活區 即時熱門文章
4
16