Jump to content

Recommended Posts

Hi

 

Simple question.

Is there a reason why you should use global over passing an argument into a function,

or visa versa?

 

example:

 

Global

$var = 1;
function test(){
    global $var;
    $var++;
    return $var;
}

 

 

Passing Argument

$var = 1;
function test($var){
    $var++;
    return $var;
}

 

 

Is it just a matter of preference?

 

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/199033-global-vs-passing-argument/
Share on other sites

Some people use the globals for "ease of use" and not having to always add that parameter to the function.

 

The preferred way, especially if you plan on distributing the script, is passing the variable as a parameter to the function. This way anyone should techincally be able to see how to use it and what it expects to be passed in, vs having to dig through all your code to find out which global variable it takes in etc.

ok great.

So they are in effect exactly the same. But passing arguments is the more preferred method.

 

I never normally use global, but a few books and training courses seem talk about using it.

I've never seen the point as I just pass the variable. So just thought I'd check I wasn't missing something.

 

Thanks for that :)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.