PHP 7 is now available with new features

1)       Return type declarations


Till previous version of PHP is considered as weak data type language, means PHP does not required you to declare variable data type. From PHP 7, developers can declare data type of the variable.

<?php
/**
 * Return type declarations


 */
//declare(strict_types=1);
function addition(int $a, int $b): int{
    return (string)($a + $b);
}
var_dump(addition(1,2));

Above code throw an error, if strict mode is enable.

2)      Scalar type declaration


The data type which holds single value is called scalar data type. Scalar data types are integer, float, Boolean and string.

PHP 7 allow developer to declare scalar data type.

<?php
/**
 * Scalar type declarations
 */
//declare(strict_types=1);
function addition(int $a, int $b) {
    return $a + $b;
}
var_dump(addition (1,2));
var_dump(addition ("1","2"));





     3)    Anonymous classes


Class and object of the class can be created in one line.

<?php
/**
 * Anonymous classes
 */
$foo = new class {
    public function foo() {
        return "bar";
    }
};
var_dump($foo,$foo->foo());

4)    Throwable 

Till the previous version of PHP, it is impossible to handle fatal errors.
In  PHP 7 , an exception will be thrown when a fatal and recoverable error occurs, rather than halting
 Script execution.

$var = 1;

try {
    $var->method(); // Throws an Error object in PHP 7.
} catch (Error $e) {
    // Handle error
}

5)    Anonymous classes


The null coalesce operator is a shorthand for checking if a value is set and not null within inline comparison.

In PHP 7, instead of doing the same old ‘isset’ check over and over again, developer can just use ‘??’ to return the value if it is set.

<?php
/**
 * Null coalesce operator
 */
 
$array = ['foo'=>'bar'];
 
//PHP5 style
$message = isset($array['foo']) ? $array['foo'] : 'not set';
echo $message.PHP_EOL;
 
//PHP7 style
$message = $array['foo'] ?? 'not set';

echo $message.PHP_EOL;

?>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
  (adsbygoogle = window.adsbygoogle || []).push({
    google_ad_client: "ca-pub-5735387273053751",
    enable_page_level_ads: true
  });
</script>

Comments