1
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

6
  • Maybe you should define the function before calling the function. Also, I don't understand why you would need to create a global function like that within a class, What are you hoping to do? Commented Jul 1, 2018 at 21:15
  • 1
    @Scuzzy I dont think that's the problem here. You can call it before it's defined. Commented Jul 1, 2018 at 21:17
  • Yes but not when nested within a class other function. Commented Jul 1, 2018 at 21:18
  • In this case I'd say the problem is that the method returns and execution is halted; therefore the function is never declared -- as you've explained in your answer. Commented Jul 1, 2018 at 21:24
  • 1
    Any particular reason why you define the function inside of your static method? Because if you do so, it will be usable in this method ONLY which makes the use of the function obsolete - you can just use its body. Commented Jul 1, 2018 at 21:26

1 Answer 1

3

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();
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

you are right. After creating the function before calling it, it works but there was an error. Which I think made calling it before declared raised the error call to undefined function
There variables declared in the static method which I wanted to use them in the function but It raises an error undefined variable. So I guess the variables are not able to be parsed into the function from the method
You can wrap it with php.net/manual/en/function.function-exists.php but really I think your implementation needs review.
Yes I declared it global because Its within a controller and I'll be calling it from other controllers and models
A public static function can be called from anywhere as well, just like your existing MainClass::myStaticMethod() method can be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.