简体   繁体   中英

Cannot Access Global Variable inside function INSIDE public function PHP

Good day. I'm trying to execute a function. i declare a global variable to get data (variable) outside the function, and the function i put inside a public function of a Class.

class Test {
    public function execute(){
        $data = "Apple";
        
        function sayHello() {
            global $data;
            
            echo "DATA => ". $data;
        
        }
        
        sayHello();
    }

}

$test = new Test;
$test->execute();

The expected result:

DATA => Apple

The real result:

DATA =>

the global variable is not getting the variable outside the function. Why it happened? Thank you for the help.

$data is not a global variable. It's inside another function, inside a class. A global variable sits outside any function or class.

But anyway your use case is unusual - there's rarely a need to nest functions like you've done. A more conventional, logical and usable implementation of these functions would potentially look like this:

class Test {
    public function execute(){
        $data = "Apple";
        $this->sayHello($data);
    }

    private function sayHello($data) {
        echo "DATA => ". $data;
    }
}

$test = new Test;
$test->execute();

Working demo: http://sandbox.onlinephpfunctions.com/code/e91b98bb15fcfa71b1c6cbbc305b5a93df678e8b

(This is just one option, but it's a reasonable one, although since this is clearly a reduced, abstract example, it's hard to be sure what your real scenario would actually require or be best served by.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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