Thursday, September 12, 2019

PHP 7 New Features Part – 2


PHP 7 New Features

Here we are going to learn PHP 7 New Features Part – 2.

Some Other Features Of PHP7:


5. Anonymous Classes:

The word Anonymous means unnamed, means which class have no names is called Anonymous Classes.
Normally, when we define any class in PHP, then it contains at least name of class. But in this type of class, no need to define the class name. We used new class Keyword to define Anonymous class in PHP7.
Suppose, we have a class and it will be used only one time during execution. Then in this situation, we need not to define a class as separate file. We can define it as Anonymous class. It saves our time.

For Example:
$message = new class{
public function display(){
echo ‘Welcome To Anonymous Class’;
}

};

$message->display();

Ans: Welcome To Anonymous Class

We can also used constructor in Anonymous Classes.


6. Error Handling:

In PHP5, when any fatal error comes, it stops the execution of script & display blank screen in front of user. In this situation, we became confuse that what is the problem in our code.
But PHP7 has introduce a new feature, where we can display an exception to user, rather than stopping the whole script.
We should not think that Fatal errors are fully gone from PHP7. It still exists to display other type of errors like running out of memory. It also shows fatal errors & stop the script, when these type of errors came.

For Example:
function sum(int $x, int $y){
return $x + $y;
}

try{
echo sum(‘abc’, ‘def’);
}catch(\TypeError $e){
echo $e->getMessage();
}

Ans: Argument 1 passed to sum() must be of the type integer, string given

Here one thing we should keep in mind that other error types like warning and notice still works same as previous. Only fatal and recoverable errors throw exceptions.

7. CSPRNG:
It stands for Cryptographically Secure PseudoRandom Number Generator.
In previous version of PHP, generally we use rand() to generate random number in integer. In PHP7, introduced two new functions to generate random numbers named random_bytes() & random_int().

Random Bytes: In this function, we always gives a single argument length, which is the length of random string.

For Example:
$bytes = random_bytes(4);
var_dump(bin2hex($bytes));

Ans: string(8) “b3c110ee”

Random Int: In this function, we always gives two parameter one is min and other is max.

For Example:
echo random_int(10000, 99999);

It always returns a random number between min and max parameters.

Use these features of PHP7 & enjoy…

No comments:

Post a Comment