4

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 :)

3
  • 3
    Why are you working with variables of which you don't know whether or not they are set? If you have user input, you'll have them in an array and can elegantly iterate over that Commented Dec 25, 2013 at 16:35
  • You're playing with the variable values, not the actual variables. Commented Dec 25, 2013 at 16:42
  • 1
    Well reason being is that for example one of the variables are $_POST['submit']. If the button has been clicked to submit a form, that variable will have a value, otherwise it won't even exist. So when it comes time to call it in an if statement to see if there is a value if(($_POST['submit'])){...} it spits out a notice telling me Undefined Index. Commented Dec 26, 2013 at 2:04

2 Answers 2

3

You can't use a function to check if a variable exists without it being initialized in the process of passing it to the function as an argument. You can, however, define an array of variable names your script requires then loop through them and check if they exist one by one. Such as:

foreach(array('username','userid','userrole','posts','dob','friends') as $var)
{
    if(!isset($$var))$$var=NULL;
}

Edit: Simplifying user4035's approach, you could get the function down to:

<?php
function init(&$var){}
init($myVariable);
var_dump($myVariable);

Or even avoid a function altogether:

<?php
array(&$var1,&$var2,&$var3);//define several variables in one shot as NULL if not already defined.
var_dump($var1);
var_dump($var2);
var_dump($var3);

Another approach would be to use extract:

<?php
$defaults=array('username'=>NULL,'userid'=>0,'userrole'=>'guest','posts'=>0,'dob'=>0,'friends'=>array());

$userid=24334;
$username='bob';
$friends=array(2,5,7);

extract($defaults, EXTR_SKIP);
echo '<pre>';
print_r(
    array(
    'userid'=>$userid,
    'username'=>$username,
    'friends'=>$friends,
    'userrole'=>$userrole,
    'posts'=>$posts,
    'dob'=>$dob)
);
echo '</pre>';

Another approach would be to temporarily disable error reporting:

<?php
$v=ini_get("error_reporting");
error_reporting(0);
echo 'One';
echo $doh;//Use an undefined variable
echo ' Two';
error_reporting($v);

I'd advise against this approach though because it is just hiding the errors rather than fixing them and will also hide errors worthy of your attention.

And my personal favorite would be to take advantage of namespaces.
Usually you'd put these into separate files but I put them into a single snippet for your convenience:

<?php
namespace //This is the global namespace
{
    $config=array('production'=>0);
}

namespace MyScript
{
   //Initialize all variables for our script
   //anything not defined here will be inherited from the global namespace
    $username=NULL;
    $userid=NULL;
    $userrole=NULL;
    $posts=NULL;
    $dob=NULL;
    $friends=NULL;

}

namespace MyScript\Main
{
//Define only two variables for our script
//Everything else will be inherited from the parent namespace if not defined
$username='Ultimater';
$userid=4;

    echo '<pre>';
    print_r(
        array(
        'userid'=>$userid,
        'username'=>$username,
        'friends'=>$friends,
        'userrole'=>$userrole,
        'posts'=>$posts,
        'dob'=>$dob,
        'config'=>$config)
    );
    echo '</pre>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is the complete answer and a great approach.
It's so simple it's beautiful :) I went with your edited approach of user4035's original code because it the simplest of them all and was the closest to my original intentions so thanks for that! Also for a very very long time (3~ years) I've been doing a dodgy and turning error reporting off to bypass it and thought it should be time to actually get rid of the notices once and for all
3

If your intention is this:

if(variable is not set)
    set variable to NULL

then it's quite easy to implement, using a reference:

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

Testing:

<?php
error_reporting(E_ALL);
function init(&$var) {
    if(!isset($var)) {
        $var = NULL;
    }
}

init($x);
var_dump($x);

Output:

NULL

6 Comments

Won't this generate an notice while passing a variable that is not set??
@HardeepSingh I just tested it: no notices generated. Try to launch my example code.
Can't believe that works... You could even factor it to: function init(&$var){}
I love it's simplicity! Went with Ultimater's answer because of the refinement of your code but otherwise yours would have been the solution I've been looking for. Thanks! :)
@SteppingHat It creates a references to variable: php.net/manual/en/language.references.php Actually, it was a surprise to me, when I saw, that creating a reference defines a variable, that it references.
|

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.