How do certain aspects of superglobals work in relation to functions in PHP?

110 Views Asked by At

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

0

There are 0 best solutions below