Image Credits: Laracasts Skills
The Realistic observation in practice is that PHP has long served as a server side web script. It also supports seamless data processing between web servers and client browsers. Besides, validating the existence of a variable is a common occurrence. For instance, utilizing the super-global arrays such as if isset ($_GET [‘variable’]) { }, is now being modified to behave more effectively by appending a coalesce (??) operator which when added to PHP code returns either:
- The result of its first operand if it exists and is not NULL or
- returns it’s second operand.
PHP 7 Null Coalesce Syntax: $_GET [‘variable’]?? “”
Earlier versions would have raised an E_NOTICE error, however, with php 7 version release, this feature has come to stay. Here are some typical examples:
1. Demonstrating NonCoalesceOperator in PHP 7
[php light=”true”]
/* Demonstrating NonCoalesceOperator */
if(!isset($_GET[‘person’]))
{ if(isset($user_name) && !empty($user_name)){ $person = $user_name; }
else { $person = ‘anonymous’; } }
else { $person = $_GET[‘person’]; }
$user_name="";
//better method to the above with PHP 7
$person = $_GET[‘person’] ?? $user_name ?: ‘anonymous’; ?>
[/php]
Output Blank on the browser: indicating no error
2. Demonstrating NonCoalesceOperator with a PHP class
[php light=”true”]
<?php /* Demonstrating NonCoalesceOperator with a class */
class absolute
{ public $absolute = ‘absolute_absolute_absolute’; }
$absolute = new absolute();
echo $absolute-&gt;absolute; // Outputs ‘aaa’ echo $absolute-&gt;basic;
// Outputs Notice: Undefined property: a::$b echo $absolute-&gt;absolute ??
‘$absolute-&gt;absolute does not exists’; // Writes ‘aaa’
// This Does not throw an error although $a-&gt;b does not exist.
echo $absolute-&gt;basic ?? ‘$absolute-&gt;basic does not exist.’;
// Writes $a-&gt;b does not exist.
// Again, this Does not throw an error although $absolute-&gt;basic and also $a-&gt;b-&gt;c does not exist.
echo $absolute-&gt;basic-&gt;cman ?? ‘$absolute-&gt;basic-&gt;cman does not exist.’;
// Writes $a-&gt;b-&gt;c does not exist. ?&gt;
[/php]
Output:
absolute_absolute_absolute Notice: Undefined property: absolute::$basic in php7_NonCoalesceOperator3.php on line 14 absolute_absolute_absolute$absolute->basic does not exist.$absolute->basic->cman does not exist.
ABOUT THE AUTHOR
About the Author: Oluwatobi Owoeye has over seventeen years’ experience in Computer Systems and Technologies with several evidence based results. He has worked in several Information Technology projects. A published Author and currently specializing in Robotics & Mobile Computing: Analytics, Computer Vision, Distributed & Parallel Computing, and Machine Learning.
Published Books: Click Here
LinkedIn Professional Network: Click Here for LinkedIn Profile
Facebook Profile: Click Here for my Facebook Handle
Tel: 2348034478125 (whats-app Number),
+2349081395295, +2348023169043, +2347052912805