【问题标题】:static method/function make call to non static function inside same class静态方法/函数调用同一类中的非静态函数
【发布时间】:2014-10-28 13:34:21
【问题描述】:

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

我正在为我的 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 静态函数 onBeforeAdminCronRun(Box_Event $event)
内?

调用内部嵌套方法/函数的正确方法是什么

startRun($event)
?

谢谢。

【问题讨论】:

    标签: php


    【解决方案1】:

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

    这意味着您需要一个类的实例(称为对象)才能使用非静态成员。

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

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


    1 您可以提出所有实例共享方法的论点,然后将对象简单地传递给方法。在幕后,这正是正在发生的事情,但在概念层面上,每个实例都有“自己的方法”。将实例共享方法实现视为一种优化。

    【讨论】:

    • 您好 cdhowie 和 tnx 的回复。那么public function startRun() 会变成public static function startRun() 吗?如何从第一个函数调用此函数(函数,因为它现在是静态的?)?我知道$this->startRun() 不会工作,因为$this 在静态函数中不起作用。以及如何从静态函数startRun() 的顶层调用我的嵌套函数?
    • 您将使用self::startRun()。您在startRun() 函数内部定义的函数只能在startRun() 内部调用,因为它们在外部不可见。就像调用任何其他函数一样调用它们。 (不要使用self::,因为它们不是类成员;它们只是常规函数,其范围恰好限于startRun() 函数。)
    • 非常感谢您在这方面的帮助并学到了很多东西(拍摄)。我遵循了您的指导方针,但遇到了另一个障碍...在我的 startRun() 函数的顶层,我尝试调用其中一个嵌套函数 (function thelog($msg)) 但收到错误“PHP 致命错误:调用未定义函数 thelog()"
    • @tSL 在定义之前您不能使用函数。 首先定义函数,然后尝试调用它们。
    • 我了解嵌套函数,例如。 thelog($msg) 不会被“定义”,直到我调用它们的父函数 startRun(),所以当我的第一个静态函数 onBeforeAdminCronRun(Box_Event $event) 从我的计费脚本接收到事件时,它会调用 startRun() 函数,所以我期待它的嵌套函数成为“定义”......不是这样吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多