Home  >  Article  >  Backend Development  >  Two new operators added to php7: '?->' and '??'

Two new operators added to php7: '?->' and '??'

PHPz
PHPzOriginal
2023-03-21 15:49:521723browse

After PHP7 was released, everyone discovered that an important change was that it enhanced strong type checking. This change is very beneficial as it helps us avoid many mistakes like referencing a variable before it has been defined.

In previous PHP versions, if we did not define a variable, using it directly would result in an Undefined variable error. However, in PHP7, we can use some new features to avoid this problem.

These new features include two new operators, namely: ?-> and ??. They can solve two different types of problems respectively.

?->Operator

In previous PHP versions, we could determine whether a variable has been defined by using the isset function. However, this only works for a single variable. If we need to check whether an object's properties are defined, we need to use some complex code to accomplish this task.

In PHP7, we can use the ?-> operator to check whether the properties of an object have been defined. This operator only returns null if the receiver of the property is null, false, or an undefined variable, otherwise it returns the value of the property. In this way, we can avoid using the property before it is defined, thereby avoiding Undefined variable errors.

<?php
$obj = null;
$value = $obj?->property;
?>

In the above code, if $obj is null, then $value will be set to null, otherwise $value will be set to the value of the property attribute of $obj.

??Operator

Another very useful new feature is the ??operator. This operator can be used to check whether a variable is defined and set a default value if not.

In previous PHP versions, we usually used the ternary operator to complete this task:

<?php
$variable = isset($variable) ? $variable : &#39;default value&#39;;
?>

In PHP7, we can use the ?? operator to replace the above code. If $variable is defined, $variable will be assigned to $result, otherwise $result will be assigned the default value.

<?php
$variable = null;
$result = $variable ?? "default value";
?>

In the above code, $result will be set to "default value" because $variable is null.

Summary

These two new operators can very effectively avoid Undefined variable errors and make our code clearer and easier maintain. When using them, we just need to pay attention to their usage and limitations.

The above is the detailed content of Two new operators added to php7: '?->' and '??'. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn