Home >Backend Development >PHP Tutorial >How Can PHP 8's Null Safe and Null Coalescing Operators Simplify Object Property Access?

How Can PHP 8's Null Safe and Null Coalescing Operators Simplify Object Property Access?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 06:21:09743browse

How Can PHP 8's Null Safe and Null Coalescing Operators Simplify Object Property Access?

Leveraging Null Safe Operator and Null Coalescing Operator in PHP 8

In PHP coding, you may encounter situations where you wish to access properties or methods of an object only if the object is not null. Traditionally, this required verbose conditional statements.

Safe Navigation in PHP 8

PHP 8 introduces the null safe operator (?->), which allows you to safely navigate objects without causing fatal errors due to null values. In conjunction with the null coalescing operator (??), you can elegantly chain operator calls.

Example

Consider the following code:

echo $data->getMyObject() != null ? $data->getMyObject()->getName() : '';

With the null safe operator, you can simplify this to:

echo $data->getMyObject()?->getName() ?? '';

In this case, if $data is null, the chain is terminated, and the result will be null.

Operators in the Chain

The operators that inspect an object's properties or methods are part of the null-safe chaining:

  • Array access ([])
  • Property access (->)
  • Nullsafe property access (?->)
  • Static property access (::)
  • Method call (->)
  • Nullsafe method call (?->)
  • Static method call (::)

Example:

$string = $data?->getObject()->getName() . " after";

If $data is null, $string becomes null. " after" since concatenation is not part of the chain.

The above is the detailed content of How Can PHP 8's Null Safe and Null Coalescing Operators Simplify Object Property Access?. 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