Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP call function within private function in class method

Tags:

php

class

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 ?

like image 761
Marcos Nakamine Avatar asked Sep 06 '26 04:09

Marcos Nakamine


1 Answers

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);
    }
}
like image 98
Baba Avatar answered Sep 07 '26 18:09

Baba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!