Learn The top 5 Features of PHP 7.4 With Examples

Learn The top 5 Features of PHP 7.4 With Examples

PHP 7.4, the next PHP 7 minor release, has been released for General Availability as of November 28th, 2019. So it’s time for us to dive into some of the most exciting additions and new features that will have made PHP faster and more reliable.

PHP 7.4, the next PHP 7 minor release, has been released for General Availability as of November 28th, 2019. So it’s time for us to dive into some of the most exciting additions and new features that will have made PHP faster and more reliable.

New features in PHP 7.4
  • Null coalescing assignment operator
  • Arrow Functions
  • Typed Properties
  • Spread Operator in Array Expression
  • Numeric Literal Separator

1.Null coalescing assignment operator

Null coalescing is a new operator introduced in PHP 7. This operator returns its first operand if it is set and not NULL. Otherwise it will return its second operand.

Let's take a look at the following example to see the difference

$username = $_GET['user'] ?? ‘nobody';


What this code does is pretty straightforward: it fetches the request parameter and sets a default value if it doesn’t exist. The meaning of that line is clear, but what if we had much longer variable names as in this example from the RFC?

$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';

In the long run, this code could be a bit difficult to maintain. So, aiming to help developers to write more intuitive code, this RFC proposes the introduction of the null coalescing assignment operator (??=). So, instead of writing the previous code, we could write the following:

$this->request->data['comments']['user_id'] ??= ‘value’;


If the value of the left-hand parameter is null, then the value of the right-hand parameter is used.
Note that, while the coalesce operator is a comparison operator, ??= is an assignment operator.

2.Arrow Functions

This is a feature that got accepted in April 2019 and loved by the PHP community. Arrow functions are extremely useful when writing callback functions (or closures, if you like). Before PHP 7.4, you had to use array_map as follows.

Consider the following example:

function cube($n){
	return ($n * $n * $n);
}
$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);

PHP 7.4 allows to use a more concise syntax, and the function above could be rewritten as follows:

$a = [1, 2, 3, 4, 5];
$b = array_map(fn($n) => $n * $n * $n, $a);
print_r($b);

Currently, anonymous functions (closures) can inherit variables defined in the parent scope thanks to the use language construct, as shown below:


$factor = 10;
$calc = function($num) use($factor){
	return $num * $factor;
};

But with PHP 7.4, variables defined in the parent scope are implicitly captured by value (implicit by-value scope binding). So we can write the whole function seen above on a single line:


$factor = 10;
$calc = fn($num) => $num * $factor;

The variable defined in the parent scope can be used in the arrow function exactly as if we were using use($var), and it’s not possible to modify a variable from the parent scope.

The new syntax is a great improvement to the language as it allows us to build more readable and maintainable code. We can also use parameter and return types, default values, variable-length argument lists (variadic functions), we can pass and return by reference, etc. Finally, short closures can also be used in class methods, and they can make use of the $this variable just like regular closures.

This RFC has been approved with 51 to 8 votes, so we can expect it to be part of PHP 7.4 additions.

3. Typed Properties (version 2.0)

Functions and class methods have already been available since PHP 5. You have seen it right?

function (int $age) {
//          ^^^
}

Since PHP 7.4, you can declare types for class properties. Here’s an example.


class MyMathClass { // <- don't get distracted
    public int $id;
    protected string $name;
    private ?int $age; // nullable types

    public static int $someStaticProp;

    private MyScienceClass $science;
    //      ^^^^^
    //      Using a class as the type       
}

All the PHP data types are allowed except void and callable.

One more thing to note is that there’s a new “Uninitialized state” (Source). If you run the following code,


class User {
    public int $id;
}
$user = new User;
var_dump($user -> id);

…what will be the result? Null? No. You’ll get an error message.

Fatal error: Uncaught Error: Typed property Foo::$bar must not be accessed before initialization

This means that there’s a new “uninitialized” state for properties introduced. And, the unset() function will work differently for types and untyped properties.

  • Types props – unset() will set the prop to uninitialized (similar to undefined in Javascript).
  • Untyped props – unset() will set prop to null.
4. Spread Operator in Array Expression

Available since PHP 5.6, argument unpacking is a syntax for unpacking arrays and Traversables into argument lists. To unpack an array or a Traversable, it has to be prepended by … (3 dots), as shown in the following example:


function dumpNames(...$names) {
    var_dump($names);
}
dumpNames('James', 'Jonty', 'Jeremy');

// will dump
// array (size=3)
//     0 => string 'James' (length=5)
//     1 => string 'Jonty' (length=5)
//     2 => string 'Jeremy' (length=6)

When you send multiple parameters into the function, PHP will combine them into one array and store in the given variable prefixed with ....

In PHP 7.4, the spread operator can be used in Array Expressions. This process is kind of the opposite of the previous one.

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];

Here, we give an array, and PHP will extract the elements of the array in the given place.

The RFC encourages using the spread operator over array_merge for better performances and to support Traversable.

Unlike argument expansion, we can use the same expansion multiple times in the same array expression (which is logical right?).


$sisterNumbers = [1,2,3];
$brotherNumber = [9,11,13];

$dadNumbers = [...$sisterNumbers, ...$brotherNumber, 42, 34]; // 1,2,3,9,11,13,42,34
$motherNumbers [...$sisterNumbers, ...$sisterNumbers]; // 1,2,3,1,2,3

  • This work for both array() and [] syntax.
  • This will only work on arrays that have numerical keys.
  • You can unpack an array returned by a function immediately. Ex: $x = [1,3, ...someFunction()]
  • You cannot unpack an array by reference.
5. Numeric Literal Separator

What a cool idea! You can now, since PHP 7.4, add underscores in numeric variables.

// previously
$price = 340523422.88; // hard to read

// now
$price = 340_523_422.88; // easy to read

PHP will ignore the _s and compile the PHP file. The only reason to add this feature is to allow developers to have more clean & comprehensible code.

The Numeric Literal Separator can be used in any numeric type (integers, float, decimal, hexadecimal, and binary).

2.554_083e-4; // float
0x46FC_FA5D;   // hexadecimal
0b0111_1101;   // binary

In this post, I mentioned the top 5 features of PHP 7.4. Hope this post will be helpful to you.

Thanks for reading !

Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx