Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: write isset function which returns value or null

I have the following code in numerous places (thousands of places) around my project:

$foo = isset($mixed) ? $mixed : null;

Where $mixed can be anything: array, array element, object, object property, scalar, etc. For example:

$foo = isset($array['element']) ? $array['element'] : null;
$foo = isset($nestedArray['element']['key']) ? $nestedArray['element']['key'] : null;
$foo = isset($object->prop) ? $object->prop : null;
$foo = isset($object->chain->of->props) ? $object->chain->of->props : null;

Is there a way to write this repeated logic as a (simple) function? For example, I tried:

function myIsset($mixed)
{
    return isset($mixed) ? $mixed : null;
}

The above function looks like it would work, but it does not in practice. For example, if $object->prop does not exist, and I call myIsset($object->prop)), then I get fatal error: Undefined property: Object::$prop before the function has even been called.

Any ideas on how I would write such a function? Is it even possible?

I realize some solutions were posted here and here, but those solutions are for arrays only.

like image 946
Leo Avatar asked Jan 12 '15 22:01

Leo


2 Answers

PHP 7 has a new "Null coalescing operator" which does exactly this. It is a double ?? such as:

$foo = $mixed ?? null;

See http://php.net/manual/en/migration70.new-features.php

like image 200
Paul Avatar answered Sep 18 '22 02:09

Paul


I stumbled across the answer to my own question while reading about php references. My solution is as follows:

function issetValueNull(&$mixed)
{
    return (isset($mixed)) ? $mixed : null;
}

Calls to this function now look like:

$foo = issetValueNull($array['element']);
$foo = issetValueNull($nestedArray['element']['key']);
$foo = issetValueNull($object->prop);
$foo = issetValueNull($object->chain->of->props);

Hopefully this helps anyone out there looking for a similar solution.

like image 33
Leo Avatar answered Sep 18 '22 02:09

Leo