Domanda

Trying to determine if a variable is one of these possible outcomes:

  1. Has a non-null value
  2. Has a value of NULL
  3. Not Set at all

I started with this:

if ( isset($value) )
  var_dump("It's set");
else
  var_dump("Not set");

That covers whether or not the variable has been set or not. However I also want to cover if the variable is null or not. Knowing the following:

$value = null;
var_dump( isset($value) );  // Returns false

So a null value is returned as not being set. So I can't do this:

if ( isset($value) )
  var_dump("It's set");
else if ( is_null($value) )   // This throws exception if $value is not set
  var_dump("It's null");
else
  var_dump("Not set");

Also can't do this:

if ( isset($value) ) {
  var_dump("It's set");
} else {
  if ( is_null($value) )
    var_dump("It's null");  // Also throws an exception because $value is not set
  else
    var_dump("Not set");
}

At first I thought there would be a simple way to do this but it is eluding me. The problem boils down to that a null value is detected as not being set, but you can't check using is_null() for a non-set value.

How do I solve this problem? Am I missing something obvious? Do I need to resort to a try catch?

And if you are curious, I'm asking this question because there is a situation where a developer could pass a variable to something, and I need to be able to differentiate between whether the developer passed the variable with a value or a NULL value or didn't pass it at all.

È stato utile?

Soluzione

The best answer I can give is that you shouldn't be trying to rely on whether or not something got set, but instead structure your code so that it is always set.

Just saw your edit.

A function parameter can have a default value, so that you know it is always set. function myFun($variable = null) will ensure that accessing $variable will never throw an exception.

Edit: If you really need to know if a parameter was passed in or not, use func_get_args(). It returns an array, and you can check its size.

function foo($bar) {
    var_dump(func_get_args());
}

foo();
foo('foo');

gives the output:

array(0) {
}
array(1) {
  [0] =>
  string(3) "foo"
}

BTW though, calling foo() with no arguments emits an error:

PHP Warning:  Missing argument 1 for foo(), called in /Users/pittsd/dev/cbsi/fly/cnet/expirement/expirement.php on line 6 and defined in /Users/pittsd/dev/cbsi/fly/cnet/expirement/expirement.php on line 2
Warning: Missing argument 1 for foo(), called in /Users/pittsd/dev/cbsi/fly/cnet/expirement/expirement.php on line 6 and defined in /Users/pittsd/dev/cbsi/fly/cnet/expirement/expirement.php on line 2

To further answer your question:

<?php
function foo() {
    if (func_get_args()) {
        $value = func_get_args()[0];
        if ($value === null) {
            echo "Have a null value. ". PHP_EOL;

        } else {
            echo "Have a value: ".$value. PHP_EOL;
        }
    }
    else {
        echo "No value passed in.". PHP_EOL;
    }
}

foo(null);
foo('foo');
foo();

outputs:

Have a null value. 
Have a value: foo
No value passed in.

Altri suggerimenti

In general you can perform your check without any exceptions this way:

if(isset($value)) {
    if($value===null) {
        // exists and null
    }
    else {
        // exists and not null
    }
}
else {
    // doesn't exists
}

EDIT:

As you mentioned in comments the code above will not works as excepted, but I got another solution to check if variable exists and is null:

var_dump(array_key_exists('value', get_defined_vars())); // false
$value = null;
var_dump(array_key_exists('value', get_defined_vars())); // true
if (!empty($value) )  //  if is not empty

or

if (empty($value))  // if is empty

Undefined variable error is a Notice error and will not stop your script execution.

Neither it will stop if you surround with try-catch{} your if clauses, so you can just suppress this error. Normally on production environments Notice errors are hidden.

You code will perfectly work if it is:

if($value == null) { // or @$value == null for suppressing this error ?
    if (count(error_get_last()) == 0) {
        echo 'null';
    } else {
        echo 'value is not set';
    }
} else {
    echo 'value is: '. $value;
}

You can check if there is an error message after testing for null, if there is, it means it's not set.

Let's test it.

First we don't pass anything. It prints:

value is not set

Now we pass $value = null;. It prints:

null

Now we pass $value = 'something';. It prints:

value is: something

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top