简体   繁体   中英

PHP - null coalescing operator

In my Symfony project I wrote a method where I need to check to tables in db.

I am looking for an id parameter that I passed in my API call. It has to be the same as for logged in user which is defined $this->getUser().

I have $account and $paymentDevice of which $account->getUser() is returning null as that entity does not exist in db. It exists in $paymentDevice->getUser() but it's like || (OR) does not get to the second value. I tried with ?: , ?? but non of the work. When I replace the order it works.

How to fix that?

public function clearSomething($id)
 {
        $type = $this->getTypeRepository()->findOneBy([
            'id' => $id
        ]);

    $account = $this->getAccountRepository()->find($id);
    $paymentDevice= $this->getPaymentDeviceRepository()->find($id);

    if ($account->getUser() === $this->getUser() || $paymentDevice->getUser() ===  $this->getUser()) {
        $this->em->remove($type);
        $this->em->flush();
    } else { throw new \Exception('Type does not belong to this Account/PaymentDevice!'); }

 }

Did you try it like this too?

$account = $this->getAccountRepository()->find($id);
$paymentDevice= $this->getPaymentDeviceRepository()->find($id);

$service = $account ?? $paymentDevice;
if ($service !== null && $service->getUser() === $this->getUser()) {
    //
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM