iamPacMan
iamPacMan

Reputation: 35

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();

Please, any ideas on how to call the function within the method?

Thank you

Upvotes: 1

Views: 2407

Answers (1)

Scuzzy
Scuzzy

Reputation: 12322

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.

Otherwise, move it outside of your class

function myFunction()
{
  echo 'hello';
}

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

Upvotes: 3

Related Questions