1

I am new to coding and this website, so I apologize in advance if I word my questions incorrectly or do not know the proper way of communicating. I have heard that using global variables is bad practice, but I am just eager to learn and understand about the vast world of coding and implement the knowledge I gain.

I came across this code on w3schools.com (https://www.w3schools.com/php/php_superglobals_globals.asp) website:

<?php 
$x = 75; 
$y = 25;

function addition() { 
    $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; 
}

addition(); 
echo $z; 
?>

The result of the code was: 100

The website then proceeded to say:

"In the example above, since z is a variable present within the $GLOBALS array, it is also accessible from outside the function!"

Is $z still considered a global variable that was declared inside the function? Can you create a variable and then just declare it in a different portion of code? I also thought you had to create a global variable before the function is invoked in order for the superglobal to be able to work inside the function?

The following code is just a simple example I tried to create:

<?php

function add() {
    echo $GLOBALS['a'] = "hello world";
}

add();

?>

My result was: hello world

Why can you run a function in PHP using a superglobal variable when the global variable was never created?

I appreciate any feedback - Thank you

  • 2
    `$GLOBALS` is an array. You _are_ creating a global variable, the moment you do an assignment like `$GLOBALS['a'] = "hello world";` – CBroe May 04 '20 at 08:49
  • @CBroe Thank you for your response - it is greatly appreciated! I think I am starting to understand how it works now. So even though the variable is created within the function, it is still considered a global variable with global scope, that is being accessed in the function as a superglobal? – spiderman0297 May 04 '20 at 09:35

0 Answers0