2014-09-03 93 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