50

I am trying to change a variable that is outside of a function, from within a function. Because if the date that the function is checking is over a certain amount I need it to change the year for the date in the beginning of the code.

$var = "01-01-10";
function checkdate() {
     if ("Condition") {
            $var = "01-01-11";
     }
}
0

5 Answers 5

77

A. Use the global keyword to import from the application scope.

$var = "01-01-10";
function checkdate(){
    global $var;  
    if("Condition"){
        $var = "01-01-11";
    }
}
checkdate();

B. Use the $GLOBALS array.

$var = "01-01-10";
function checkdate(){
    if("Condition"){
        $GLOBALS['var'] = "01-01-11";
    }
}
checkdate();

C. Pass the variable by reference.

$var = "01-01-10";
function checkdate(&$funcVar){  
    if("Condition"){
        $funcVar = "01-01-11";
    }
}
checkdate($var);
Sign up to request clarification or add additional context in comments.

6 Comments

For the third example (C), should the first and last lines reference $var or $funcVar...or should that last line be $var = checkdate($var);?
@JeromyFrench The first and last line refer to the variable in the outer scope, named $var. Inside the function it may have any other name, so I chose $funcVar specifically to illustrate that the name may be different. Regarding $var = checkdate($var);, the whole purpose of the example was to show passing by reference and changing the passed variable directly in the function.
Ok, I think I get it. function checkdate(&$funcVar) combined with checkdate($var); maps the outer $var to the inner $funcVar.
There is also another option, you pass a class/object variable to your function, then it will be passed by reference. See stackoverflow.com/a/9696799/5842403 to avoid this you have to clone it
Another option would be to use class/object value inside a method, and reference to it by $object->var or by Class:$var
|
45

Just use the global keyword like so:

$var = "01-01-10";
function checkdate(){
     global $var;

     if("Condition"){
            $var = "01-01-11";
      }
}

Any reference to that variable will be to the global one then.

2 Comments

but i want to change the global variable so whatever i set var to, will it effect the global variable outside of the function?
That is what this will do. Using global changes the variable $var inside the function to point to the global one. When you change that variable inside the function, it will change the global one.
8

All the answers here are good, but... are you sure you want to do this?

Changing global variables from within functions is generally a bad idea, because it can very easily cause spaghetti code to happen, wherein variables are being changed all over the system, functions are interdependent on each other, etc. It's a real mess.

Please allow me to suggest a few alternatives:

  1. Object-oriented programming

  2. Having the function return a value, which is assigned by the caller.

    e.g. $var = checkdate();

  3. Having the value stored in an array that is passed into the function by reference

    function checkdate(&$values) {
       if (condition) {
          $values["date"] = "01-01-11";
       }
    }
    

Comments

6

Try this pass by reference

  $var = "01-01-10";
    function checkdate(&$funcVar){  
        if("Condition"){
            $funcVar = "01-01-11";
        }
    }
    checkdate($var);

or Try this same as the above, keeping the function as same.

 $var = "01-01-10";
    function checkdate($funcVar){  
        if("Condition"){
            $funcVar = "01-01-11";
        }
    }
    checkdate(&$var);

1 Comment

The second snippet gives Parse error: syntax error, unexpected token "&". 3v4l.org/FrkC0
0

This task is a common XY Problem.

It is poor design to create a function/method which needs access to data not declared in the function/method signature.

This is a code smell.

No modern code containing custom functions should be passing data into the limited scope using global or super-globals (e.g. $GLOBALS, $_POST, $_GET, $_REQUEST, $_SESSION). In fact, for maximim utility, you should never write a function signature or body which contains global variables. Functions should be completely ignorant of where their input data was sourced from -- that is business of the calling script, not the function being called.

Ideally, you pass all required data as parameters to your function. If you cannot (or choose not to) return data from your function, then you can modify any number of parameters by reference (add & before the parameter(s) in the signature).

Do not be tempted to reduce the parameter count. It is too common to see scripts which have the database connection as global $mysqli; as the first line in the function body -- don't do that.

Also ensure that functions only do one thing. If a function needs to do two things, break the function down into two child functions called by the parent function and pass required data where needed. This will improve maintainability.

We should only see snippets like:

Returning data:

function foo(bool $bar): bool
{
    return !$bar;
}

$bar = false;
var_export(foo($bar)); // true

Or modifying data by reference:

function foo(bool &$bar): void
{
    $bar = !$bar;
}

$bar = false;
foo($bar);
var_export($bar); // true

There might be some edge cases where using a combination of the two above approach seems suitable -- but endeavour to avoid such structures as much as possible.


As a related side step on this topic, if you need to modify data within a function of which you do not have control of the signature, pass the variable into the function scope by reference use (&$data). If you need to pass in but not modify the passed in data, then referencing is not necessary use ($data).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.