简体   繁体   English

PHP在类的静态方法中调用函数

[英]PHP Calling a function within a static method of a class

class MainClass {

    public static function myStaticMethod(){
        return myFunction();

        function myFunction(){
            echo 'hello';
        }
    }
}

The above code when executed returns call to undefined function myFunction(); 执行上面的代码返回对未定义函数myFunction();调用myFunction();

Please, any ideas on how to call the function within the method? 请问有关如何在方法中调用函数的任何想法?

Thank you 谢谢

Move the function deceleration to before you attempt to use it when defining functions within other functions... 在定义其他功能中的功能时,将功能减速移动到尝试使用之前...

class MainClass
{
  public static function myStaticMethod()
  {
    function myFunction()
    {
      echo 'hello';
    }
    return myFunction();
  }
}

MainClass::myStaticMethod(); // No error thrown

Note that repeat calls to MainClass::myStaticMethod will raise Cannot redeclare myFunction() unless you manage that. 请注意,重复调用MainClass :: myStaticMethod将引发Cannot redeclare myFunction()除非您管理它。

Otherwise, move it outside of your class 否则,将它移到课堂外

function myFunction()
{
  echo 'hello';
}

class MainClass
{
  public static function myStaticMethod()
  {
    return myFunction();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM