2014-09-03 91 views
0

我還沒有理解靜態和非靜態方法/函數(我寧願說方法/函數,因爲我還沒有清楚的區別)。靜態方法/函數調用同一類中的非靜態函數

我正在爲我的boxbilling(BB)系統構建一個擴展模塊(模塊),我有點卡住了。

這個類可以掛鉤BB的事件,並允許我執行其他操作。

class Blah_Blah 
{ 

    //The method/function that receives the event:  
    public static function onBeforeAdminCronRun(Box_Event $event) 
    { 
     startRun($event); //call "main" method/function to perform all my actions. 
    } 

我從BB使用的另一個類複製編碼風格。所以我最終創建了一個主函數,裏面有幾個嵌套函數。

public function startRun($event) // I believe that "public" exposes this method/function to the calling script, correct? if so, I can make private or remove "public"?? 
{ 
    // some parameter assignments and database calls goes here. 
    // I will be calling the below methods/functions from here passing params where required. 
    $someArray = array(); // I want this array to be accessible in the methods/functions below 

    function firstFunction($params) 
    { 
    ...some code here... 
    return; 
    } 
    function secondFunction() 
    { 
    ...some code here... 
    loggingFunction('put this in log file'); 
    return; 
    } 
    function loggingFunction($msg) 
    { 
    // code to write $msg to a file 
    // does not return a value 
    } 
} 

什麼叫

startRun($event)
public static function onBeforeAdminCronRun(Box_Event $event)
正確的方法是什麼?

startRun($event)
裏面調用嵌套方法/函數的正確方法是什麼?

謝謝。

回答

1

剛開始時,先去了一些OOP術語:函數是靜態的,方法是非靜態的(即使兩者都是使用PHP中的關鍵字function定義的)。靜態類成員屬於類本身,因此它們只有一個全局實例。非靜態成員屬於類別的實例,因此每個實例都有自己的這些非靜態成員的副本。

這意味着您需要一個類的實例 - 稱爲對象 - 才能使用非靜態成員。

在你的情況下,startRun()似乎沒有使用該對象的任何實例成員,所以你可以簡單地使它成爲靜態來解決問題。

在你的情況下,如果你需要在startRun()之內嵌套這些函數,或者你應該使它們成爲這個類的函數或方法,那麼還不清楚。可以有嵌套函數的有效情況,但由於問題中的信息有限,很難說這是否是這種情況。


你可以做所有的實例共享方法和對象僅僅是傳遞給方法的參數。事實上,這正是發生的事情,但在概念層面上,每個實例都有「自己的方法」。將實例共享方法實現視爲優化。

+0

嗨cdhowie和tnx的響應。所以'公共函數startRun()'將成爲'公共靜態函數startRun()'?如何從第一個函數調用此函數(函數,因爲它現在是靜態的?)?我明白'$ this-> startRun()'不會起作用,因爲'$ this'在靜態函數中無效。以及如何從靜態函數'startRun()'的頂層調用我的嵌套函數? – tSL 2014-09-03 23:29:49

+0

你可以使用'self :: startRun()'。您在'startRun()'函數內定義的函數只能在'startRun()'中調用,因爲它們在其外部不可見。只要打電話給他們就好像你會打電話給任何其他功(不要使用'self ::',因爲它們不是類成員;它們只是常規函數,它們的作用域限於'startRun()'函數。) – cdhowie 2014-09-03 23:40:56

+0

我真的很感激你的幫助,並學習了很多東西(鏡頭)。我遵循了你的指導原則,但遇到了另一個障礙......在我的'startRun()'函數的頂層,我嘗試調用其中一個嵌套函數('function thelog($ msg)'),但接收到錯誤「PHP致命錯誤:調用未定義函數thelog()」 – tSL 2014-09-04 01:31:19