[php: Null coalescing operator] Null and Undefined safe operator in PHP7. #php
<?php
// $null_or_undefined = 'there!';
$case1 = $null_or_undefined ?? 'nothing!';
echo 'case1: ' . var_export($case1, true) . PHP_EOL; // case1: 'nothing!'
$definiedVar = 'content';
$case2 = $definiedVar ?? 'nothing!';
echo 'case2: ' . var_export($case2, true) . PHP_EOL; // case2: 'content'
// $_POST['isThere?'] = 'there!';
$case3 = $_GET['isThere?'] ?? $_POST['isThere?'] ?? 'nothing!' ;
echo 'case3: ' . var_export($case3, true) . PHP_EOL; // case3: 'nothing!'
// Safe foreach
// $defined = [100, 200, 300, 400];
foreach ($defined ?? [] as $key => $value) {
echo 'case4: ' . $key . ' => ' . $value . PHP_EOL; // No printing.
}
// Undefined safe.
class Klass
{
public $object;
public function __construct()
{
$this->object = new stdClass();
// $this->object->property = 'exists'; // Be undefined.
}
}
$Klass = new Klass();
echo $Klass->object->property ?? 'none'; // none.
echo PHP_EOL;
$array = [
'key' => [
// 'innerKey' => 'value', // Be undefined.
],
];
echo $array['key']['innerKey'] ?? 'none'; // none
echo PHP_EOL;