QUIZGUM

Coding Class

Quizgum : Using Global Variables in Functions

Using Global Variables in Functions

You learned about global and local variables earlier.
Now let's look at how to use global variables in a function.
Use the global keyword in a function.

Using the global keyword

global global variable name

Enter the global variable name to use after entering the global keyword in the function.
As always, we'll look at an example.

<?php
    $disney = 'mickey';

    function func(){
        echo $disney;
        return;
    }

    func();
?>

If you look at the result of the code above, you can see that nothing is executed.
Let's use the global keyword in the function func.

<?php
    $disney = 'mickey';

    function func(){
        global $disney;
        echo $disney;
        return;
    }

    func();
?>

Result of the code above

php image

Unlike the first example, you can use the disney variable inside a function by using the global keyword in the function.
Many global variables can use the global keyword.

Using the global keyword with multiple global variables

global global variable name, global variable name

Then shall we look at an example?

<?php
    $disney = 'mickey';
    $marvel = 'iron man';

    function func(){
        global $disney, $marvel;
        echo $disney.', '.$marvel;
        return;
    }

    func();
?>

result

php image

Yes, we learned about global keywords. ^^