簡體   English   中英

PHP類函數既不是方法也不是靜態的

[英]PHP Class functions that are neither methods nor static

我想在我的班級中使用一個函數來執行一個簡單的任務,例如:

function hello($name) { return 'hello '.$name; }

即不一定是靜態的(雖然我想它可能是),但與對象無關(沒有引用$ this)。

我是否使用靜態功能? 即。

static function hello($name){return 'hello '.$name;}

並使用$string = ClassName::hello('Alex');調用它$string = ClassName::hello('Alex');

或者,還有更好的方法?

謝謝!

不需要調用對象實例並且應該能夠在沒有對象實例的情況下執行的類方法應聲明為static。

靜態方法沒有$ this,應該作為ClassName :: methodName()調用。

靜態方法可以訪問其類的靜態成員變量。

靜態函數應該是靜態函數。
如果它是無狀態的,那么使用靜態。

您還可以在類* Utils中封裝類似函數的組。 所以這些功能就像幫手一樣

class StringUtils{
function splitBy($delimeter,$val){....}
}

than you call it StringUtils::splitBy(..)

意思是如果它與對象無關,請將其分開。

您可以將utils文件夾帶到每個項目中,並在其上和之后重復使用....

  1. 這個班的這個功能是什么? 如果它不屬於它 - 只需移動到其他地方
  2. ...如果屬於那么問題是可以在不創建對象的情況下調用它

如果沒有引用$ this(或者可能將來引用$ this),請將其設置為靜態。

我之所以這樣說是因為有時候我會選擇:

static function hello( $name ) { return 'hello '.$name; }

經過幾個月的開發和擴展程序后,我覺得需要引用$ this,如:

function hello( $name ) { return $this->helloInLanguage[ $this->language ].' '.$name; };

暫無
暫無

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

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