簡體   English   中英

如何在PHP中將方法聲明為公共但非靜態?

[英]How do you declare a method as public but non-static in PHP?

問題出在標題中。

默認情況下它們是非靜態的:

public function method() {

}

如果你靜態地調用它,你將得到一個E_STRICT ,但我認為你不能輕易地強制它只能在一個實例上調用 - 如果你試圖檢查 $this我認為你會得到一個錯誤。 您可以按照Artefacto的說法進行isset($this) ,如果未設置則拋出異常。

<?php
class abc() {

 public function foo() {
     ...
 }
}

$c = new abc();
$c->foo();
?>
<?php
class abc() {

 public function foo() {
     if (!isset($this)) {
         throw new Exception('Method is non-static.');
         exit();
     }
 }
}

$c = new abc();
$c->foo();
?>

沒有測試過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM