6

I try call Test3 function, but returned this error: "Fatal error: Call to undefined function".

Here is an example:

class Test {
    public Test1(){
        return $this->Test2();
    }

    private Test2(){
        $a = 0;
        return Test3($a);

        function Test3($b){
            $b++;
            return $b;
        }
    }
}

How to call Test3 function ?

4
  • 4
    Why are you nesting functions like this in the first place? Make Test3 a separate method in your class, and then you can call it as $this->Test3() and your won't run into problems like this Commented May 7, 2013 at 14:47
  • There is no use for nested php functions, they could be treated as a side effect of the parser. Commented May 7, 2013 at 14:51
  • 3
    public Test1(){ what language is this? Commented May 7, 2013 at 14:52
  • Thanks Mark Baker, and thanks to all. Your tip worked. But it is possible in this format? Commented May 7, 2013 at 14:55

2 Answers 2

10

From PHP DOC

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

Use Closures 

$test = new Test();
echo $test->Test1();

Modified Class

class Test {

    public function Test1() {
        return $this->Test2();
    }

    private function Test2() {
        $a = 0;

        $Test3 = function ($b) {
            $b ++;
            return $b;
        };

        return $Test3($a);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Not sure if you wanted a closure or if your 'inner' function was a typo.

If it was meant to be a separate method then the below is the correct syntax:

class Test 
{

  public function Test1() 
  {
    return $this->Test2();
  }

  private function Test2() 
  {
    $a = 0;
    return $this->Test3($a)
  }

  public function Test3($b)
  {
    $b++
    return $b;
  }

}

Comments

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.