Is there anything similar to the Optional Chaining (optional chaining) of Javascript in PHP?

Asked

Viewed 96 times

4

We know that in Javascript:

The optional chaining (optional chaining operator) ?. allows the reading of the value of a property located internally in a chain of connected objects, without the validation of each chain reference being expressively performed. 1

That is, it is a safe way to access properties of nested objects, even if an intermediate property does not exist.

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// output: undefined

console.log(adventurer.someNonExistentMethod?.());
// output: undefined

console.log(adventurer.cat.name);
// output: Dinah

console.log(adventurer?.cat?.cat?.name);
// output: undefined
// nenhum erro será lançado

A friend of mine from college, thought it was wonderful this feature of Javascript and he wanted to know if it exists in PHP (I didn’t know how to answer). The goal was to simplify a code snippet infernal of it, demonstrated below:

...

if ($session !== null) {
    $admin = $session->adminUser;
    ...
    if ($admin !== null) {
        $credential = $admin->getAuthCredentials();
        ...
        if ($credential !== null) {
            $data = $credential->email;
            ...
        }
        ...
    }
    ...
}

Detail, that ladder caused by ifs grows even more..., he just sent an excerpt to exemplify.

In Javascript it would be something like:

const credential = session?.adminUser?.getAuthCredentials?.()
const data = credential?.email

Is there anything equivalent to the optional Javascript chaining operator in PHP? If not, indicate me forms, methods, refuse to simplify the above code example. Links to other answers are accepted.

OBS1: The PHP version he used was the 7.2.

OBS2: I don’t know anything about PHP and I haven’t found anything related here on Sopt. It can also serve to help others who may have the same doubt and curiosity.

  • 1

    You just want to know if it exists? That’s what the question gave me to understand. In this case, I think the only current response already responds; or also wants to know how it works and some important details?

  • 1

    Yes, please. :)

1 answer

2


  • Putzs, only in PHP 8? Someone will be sad.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.