How to use the global keyword in PHP?

Member

by jerad , in category: PHP General , 6 months ago

How to use the global keyword in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 6 months ago

@jerad 

In PHP, the global keyword is used to access a global variable inside a function. A global variable is a variable that is defined outside of a function and can be accessed from any part of the code.


Here is an example of how to use the global keyword in PHP:

1
2
3
4
5
6
7
8
9
$counter = 0; // define a global variable

function increment_counter() {
    global $counter; // access the global variable
    $counter++;
}

increment_counter(); // call the function
echo $counter; // output: 1


In the above example, we define a global variable $counter and a function increment_counter() that increments the value of $counter by 1. Inside the function, we use the global keyword to access the global variable $counter.


When we call the increment_counter() function and then output the value of $counter, it will display 1 because the function has incremented the value of the global variable.


Note that using global variables can make your code more difficult to maintain and debug, so it's generally a good practice to avoid them if possible.