Introduction:
Learn about global variables in PHP and how they allow you to access data from anywhere in your script. This lesson covers the basics of using global variables, provides examples, and discusses best practices. Gain insights into creating PHP applications with practical demonstrations.
In PHP, $GLOBALS is a superglobal variable that is used to access global variables from anywhere in a script, regardless of the scope.
It is an associative array where each key is the name of a global variable, and the corresponding value is the data stored in that variable.
Here’s a simple example:
<?php $x = 10; $y = 20; function addGlobalVariables() { // Accessing global variables using $GLOBALS $GLOBALS['sum'] = $GLOBALS['x'] + $GLOBALS['y']; } addGlobalVariables(); // Accessing the global variable set in the function echo $sum; // Outputs 30 ?>
It’s important to note that using global variables extensively can make code harder to maintain and debug. It is generally considered good practice to minimize the use of global variables and prefer passing variables explicitly between functions or using other means of encapsulation.
Here’s a step-by-step guide:
Define Global Variables:
Start by declaring your global variables outside of any function or class.
<?php $globalVariable1 = "Hello"; $globalVariable2 = 42; ?>
Access Global Variables Inside a Function:
Use the $GLOBALS superglobal to access the global variables within a function.
<?php function myFunction() { echo $GLOBALS['globalVariable1']; // Outputs: Hello echo $GLOBALS['globalVariable2']; // Outputs: 42 } myFunction(); ?>
You can also declare global variables outside functions or classes.
<?php $globalVariable1 = "Hello"; $globalVariable2 = 42; ?>
Since the variables are declared outside functions, they are accessible globally.
<?php function myFunction() { global $globalVariable1, $globalVariable2; echo $globalVariable1; // Outputs: Hello echo $globalVariable2; // Outputs: 42 } myFunction(); ?>
Remember, while global variables provide a convenient way to share data between different parts of your script, excessive use of global variables can make code harder to understand and maintain.
complete example in html with explanation
index.php:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Global Variables Example</title> </head> <body> <h2>Sum Calculator</h2> <!-- HTML form --> <form method="post" action="calculate.php"> <label for="num1">Number 1:</label> <input type="text" name="num1" required> <label for="num2">Number 2:</label> <input type="text" name="num2" required> <button type="submit">Calculate Sum</button> </form> </body> </html>
create :calculate.php:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calculation Result</title> </head> <body> <h2>Calculation Result</h2> <?php // Check if form is submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Accessing form data using $_POST $num1 = $_POST["num1"]; $num2 = $_POST["num2"]; // Validate input (you may want to perform more robust validation) if (!is_numeric($num1) || !is_numeric($num2)) { echo "<p>Please enter valid numbers.</p>"; } else { // Creating a global variable to store the sum $GLOBALS['sum'] = $num1 + $num2; // Displaying the result echo "<p>Sum of $num1 and $num2 is: " . $GLOBALS['sum'] . "</p>"; } } else { // If form is not submitted, display a message echo "<p>Please submit the form to calculate the sum.</p>"; } ?> <p><a href="index.php">Go back to the form</a></p> </body> </html>
Explanation:
index.php:
This is the main HTML file with a form that takes two numbers as input.
The form’s action attribute is set to “calculate.php,” which is the script that will handle the form submission.
calculate.php:
You can run this example by saving these files in the same directory and accessing index.php in a web browser. Enter two numbers in the form, submit it, and the calculated sum will be displayed on the result page.
Another example
Create :index.php:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Click Counter</title> </head> <body> <h2>Click Counter</h2> <p>Click the button to increase the count:</p> <!-- HTML button --> <button onclick="updateCount()">Click me</button> <!-- Display the click count using PHP --> <p>Click count: <?php echo $GLOBALS['clickCount']; ?></p> <!-- JavaScript function to trigger the PHP script --> <script> function updateCount() { // Use AJAX to call the PHP script asynchronously var xhr = new XMLHttpRequest(); xhr.open("GET", "updateCount.php", true); xhr.send(); // Update the count displayed on the page (optional) var currentCount = parseInt(document.getElementById("clickCount").innerText); document.getElementById("clickCount").innerText = currentCount + 1; } </script> </body> </html>
Create :updateCount.php:
<?php // Initialize the click count if it doesn't exist if (!isset($GLOBALS['clickCount'])) { $GLOBALS['clickCount'] = 0; } // Increment the click count $GLOBALS['clickCount']++; // You can perform other operations here if needed // Optionally, you can send a response (e.g., for AJAX requests) echo "Click count updated to: " . $GLOBALS['clickCount']; ?>
Explanation:
index.php:
updateCount.php:
To run this example, save these files in the same directory, and open index.php in a web browser. Each time you click the button, the click count will increase, and the updated count will be displayed on the page without refreshing.
An application by this lesson with explanation
index.php:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> Information App</title> </head> <body> <h2> Information App</h2> <!-- HTML form --> <form method="post" action="processForm.php"> <label for="name">name:</label> <input type="text" name="name" required> <label for="email">Email:</label> <input type="email" name="email" required> <button type="submit">Submit</button> </form> <!-- Display information using PHP --> <?php if (isset($GLOBALS['Info'])) { echo "<h3>Entered Information:</h3>"; echo "<p>name: " . $GLOBALS['Info']['name'] . "</p>"; echo "<p>Email: " . $GLOBALS['Info']['email'] . "</p>"; } ?> </body> </html>
processForm.php:
<?php // Initialize the information array if it doesn't exist if (!isset($GLOBALS['Info'])) { $GLOBALS['Info'] = []; } // Process the form data and store it in the global variable if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST["name"]; $email = $_POST["email"]; // You can perform additional validation if needed // Store the information in the global variable $GLOBALS['Info'] = [ 'name' => $name, 'email' => $email, ]; } // Redirect back to the main page header("Location: index.php"); exit; ?>
Explanation:
index.php:
processForm.php:
To run this application:
This example demonstrates the use of global variables to store information across requests. However, keep in mind that in more complex applications, using global variables may not be the most optimal approach, and other methods like sessions or databases may be more suitable.
Here’s a quiz about PHP and global variables.
Each question has multiple-choice answers, and the correct answer is indicated with the (Correct) tag.
a. A variable declared inside a function
b. A variable accessible from anywhere in the script (Correct)
c. A variable with a global scope
a. $GLOBALS (Correct)
b. $_POST
c. $_GET
a. Increased code readability
b. Code organization becomes more straightforward
c. Maintenance challenges and potential conflicts (Correct)
a. To store session data
b. To access global variables from anywhere in the script (Correct)
c. To retrieve form data
a. $globalVar;
b. global $globalVar; (Correct)
c. var $globalVar;
a. Use global variables extensively for simplicity
b. Minimize the use of global variables and prefer other means of encapsulation (Correct)
c. Always declare variables within functions
a. Using a local variable
b. Using a session variable
c. Using the $GLOBALS superglobal (Correct)
a. Displays the click count
b. Handles form submission
c. Updates the global variable and sends a response (Correct)
a. Validates form data
b. Sends an AJAX request to updateCount.php (Correct)
c. Displays the click count on the page
a. Retrieves the click count from the server
b. Updates the displayed click count on the page (Correct)
c. Clears the click count
a. Displays an error message
b. Redirects back to the main page (Correct)
c. Ends the script execution
a. text
b. email (Correct)
c. input
a. Declares a global variable
b. Initializes the global variable as an empty array (Correct)
c. Displays information
a. Global variables improve code organization
b. Global variables may lead to maintenance challenges and potential conflicts (Correct)
c. Global variables speed up the execution of scripts
a. Cookies
b. Sessions (Correct)
c. Local variables