Using a function to initialise a variable if it not set - PHP

Viewed 4633

Upon executing a script, sometimes the variable will be set, and sometimes it won't. The times that it isn't, I'm given a notice that the variable is not defined.

In efforts to clear the notice, I simple added the following code

if(!isset($var)) {
    $var = NULL;
}

That works just as needed because it tests if the variable isn't already set so that we don't set something that we need to NULL. But in a file where there are over 60 variables that are of this case and more to come, I thought creating a simple function to do so would be easier. So I started with this:

function init($var) {
    if(!isset($var)) {
        return $var = NULL;
    }
}

Obviously that doesn't work and is also riddled with errors that will annoy most programmers out there (such as the !isset() inside a function, not supplying a return statement in case the if statement is false, etc.) but that's just to give you the basic jist of what I need so in the code I can just call init($var); to test if the variable isn't already set, and then creates one and sets it to NULL to avoid the notice.

Is this even possible? To use a function to test if a variable is already set outside of the function? Thanks in advance :)

2 Answers
Related