静态方法/函数调用同一类中的非静态函数


static method/function make call to non static function inside same class

我还不了解静态和非静态方法/函数(我宁愿说方法/函数,因为我还不太清楚区别)。

我正在为我的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
  }
}

在BeforeAdminCronRun(Box_event$event)上的

公共静态函数内部调用
startRun($event?

调用

startRun($event)
内部嵌套方法/函数的正确方法是什么?

谢谢。

先去掉一些OOP术语:函数是静态的,方法是非静态的(尽管两者都是用PHP中的关键字function定义的)。静态类成员属于类本身,因此它们只有一个全局实例。非静态成员属于类的实例,因此每个实例都有自己的这些非静态成员1的副本。

这意味着您需要一个称为对象的类实例,以便使用非静态成员。

在您的情况下,startRun()似乎没有使用对象的任何实例成员,因此您可以简单地将其设置为静态以解决问题。

在您的情况下,尚不清楚是否需要在startRun()中嵌套这些函数,或者是否应该使它们成为类的函数或方法。嵌套函数可能存在有效的情况,但由于问题中的信息有限,很难说这是否是一种情况。


1您可以提出所有实例共享方法的论点,并且对象只需传递给方法即可。在引擎盖下,这正是正在发生的事情,但在概念层面上,每个实例都有"自己的方法"。将实例共享方法实现视为一种优化。