Another question Re: Globals

Ok I have another question regarding globals.

If I have this for example
<?php

    global $life, $num;
        $life = 42;
        $num = 32;
        
function meaningOfLife()
{    
            echo "The meaning of life is " . $life . ".</br/>";
            echo "The second number is " . $num . ".";
}
meaningOfLife();
?>

With this code, the script pops two errors.
Warning: Undefined variable $life in H:\XAMPP\htdocs\Runes\Vars.php on line 11
The meaning of life is .

**Warning**: Undefined variable $num in **H:\XAMPP\htdocs\Runes\Vars.php** on line **12**
The second number is .

Why are the vars considered undefined in this case. It seems to me if I declare both of them as globals anywhere inside the script they should be available to any function, no matter how many functions I use.

If I add a second function like this
<?php
function meaningOfLife()
{
global $life;
global $num;
$life = 42;
$num = 32;
echo "The meaning of life is " . $life . “.</br/>”;
echo "The second number is " . $num . “.”;
}
meaningOfLife();

function meaningOfLife2()
{    

            echo "The second meaning of life is " . $life . ".</br/>";
            echo "The second second number is " . $num . ".";
}
meaningOfLife2();
?>

Then I get the error message about undeclared vars in the second function. To me, this just seems like a waste to declare vars as global unless I am just missing something.

I have tried reading up on this but nothing seems to address this question.

Thanks again!
Jim

The global keyword only has meaning, and only ‘works’, inside of a function/class-method definition, and even then don’t use it since it breaks program scope. The data inputs to a function/class-method should be supplied as call-time parameters so that you can see the total affect of the call at the point of making the call. By using the global keyword to make your code ‘work’, you are creating more work for yourself or anyone who needs to deal with your code because they will now need to learn and keep track of all the various global’ed variables, which must now be uniquely named so as to not interfere with each other. This is a ‘deal breaker’ in large code projects and when multiple programmers are working on a project. Think of how hard it would be to use PHP if all the php functions used global variables inside of every function?

1 Like

I have used global’s in some cases because they are handy. Also, they save passing huge arrays to functions. The use of them should be limited as they are not needed most of the time. Functions are used only if you need to run repetitive code over and over throughout your page’s code.

Your example “meaningOfLife()” does not do anything, but, it “wants” to use two inputs. Therefore the function should be set up for two inputs.

function meaningOfLife($life, $num) {
    do something with the inputs
}

The entire reason of this is to allow for recursive calls. You can have the function call itself as many times as needed to accomplish your task. Each call of the function uses it’s own version of the variable’s data that are given to it as inputs. Often, such as parsing thru folder structures looking for all images, you need to call a function over and over when you get to a sub-folder. Functions were created to make life easier. Hope this helps make more sense of it all…

This is just a little script to try to get me from PERL to php. Think of it as a learning opportunity. I thank both of you for the replies. But what is the thought behind calling a var a global if it is not truly global? To me, global implies that it can go anywhere, be used by any function, etc. But if I declare a global outside of a function then that function does not have access to a supposedly global var then it seems pretty useless. I am off to do some more reading on globals. :slight_smile:

It is very simple. It is called SCOPE. The scope of all variables in any PHP code is global but only to that page. The scope of functions are limited to the function only. If you want to access the variables in the main page of your code from inside a function, you need to tell the function to use the outside value of them.

There are thousands of sites that discuss this, but, it boils down to just what I said. Here is a site that explains in a different manner. ( Sorry, it also introduces STATIC variables, too. ) PHP Scope

First, ErnieAlex, no apologies needed for the static vars. That is something I will delve into in a few minutes. But, here is what I took away from the discussion about globals and the reading I did. Just want a quick opinion on the thought and syntax that went into this. Everything looks ok to me, but there may be something I missed. I was just playing around with different ways to manipulate the vars so I made sure I had a least a rudimentary grasp.

<?php

$life = 42;

function meaningOfLife()
{    
            echo "The meaning of life is " . $GLOBALS['life'];
}

function meaningOfLife2()
{    
    $GLOBALS['life']++;
            echo "The second meaning of life is " . $GLOBALS['life'];
}

function meaningOfLife3()
{    
            echo "The third meaning of life is " . $GLOBALS['life'] - 3;
}

function meaningOfLife4()
{    
    $GLOBALS['life'] = $GLOBALS['life'] - 1;
            echo "The fourth meaning of life is " . $GLOBALS['life']; 
}

echo $GLOBALS['life'];
echo "<p/>";
meaningOfLife();
echo "<p/>";
meaningOfLife2();
echo "<p/>";
meaningOfLife3();
echo "<p/>";
meaningOfLife4();
?>

And the output was just what I expected…
42

The meaning of life is 42

The second meaning of life is 43

The third meaning of life is 40

The fourth meaning of life is 42

Yes, that works, but, it is not the way a professional programmer would do it.

Nornaly, you never want to actually use the $GLOBALS directly. You can, it says so in PHP.NET.
But, you normally would do it this way:

$life = 42;
function meaningOfLife($life) {
   echo "Meaning of life is " . $life;
}
meaningOfLife($life);

This makes it messy really, but, your example is an odd one. Examples show ways to do things, but, they do not explain the real process in a nice way. Your example shows how you can use the $GLOBALS array. This works and you can use it. But, functions were not really designed for that type of process. In your example, that process would not need a function.

And, most functions are designed to do repetitive tasks that are mostly processed only in the function and returns a result. For example, a complicated math calculation. In my sites, I just declare the global variable at the top of the function which makes it clear that the function is sharing the code with the rest of the code on the page.

Not sure if this extra info make it harder or easier. Good luck…

I think this is a little more elegant and a little closer to what would normally be used.

$myArr = [
“l1” => “42.”,
“l2” => “complicated.”,
“l3” => “different for everyone.”
];

function out($myArr) {
foreach($myArr as $val) { // Normal Variable
echo " The meaning of life is " . $val . “<br/>”;
}
}

out($myArr);

This outputs exactly what I expected…
The meaning of life is 42.
The meaning of life is complicated.
The meaning of life is different for everyone.

In case it hasn’t already been stated enough different ways in this thread - a well-written function should be general-purpose, reusable, responsible for doing one thing, accept all inputs as call-time parameters, and return the result to the calling code (so that you can use the result in different contexts, even as an input to other function calls.) This is known as the black-box model. Using the global keyword or the $GLOBALS array to make a function ‘work’ results in spaghetti code that takes more effort and time to write, debug, and maintain.

1 Like

I did edit my code. If you take a quick look again, I eliminated the global.

I am constantly changing things as I pick up more from my reading.

Thank you for your reading and feedback though!

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service