DEV Community

Cover image for 5 tips in PHP 🐘

5 tips in PHP 🐘

Saymon Tavares on August 24, 2021

In this article, I’ll show you 10 tips that can improve your PHP code πŸ” 🐘 In order to make this article easier to read, I’ll write some pieces of c...
Collapse
 
lito profile image
Lito
    private function getAccessor(): PropertyAccess
    {
        return $this->propertyAccessor ?? $this->propertyAccessor = PropertyAccess::createPropertyAccessor(); 
    }
Enter fullscreen mode Exit fullscreen mode

Is same as:

    private function getAccessor(): PropertyAccess
    {
        return $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor(); 
    }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nfcristea profile image
Florin Cristea • Edited

??= will also assign the value on first call, besides checking if it's set, meaning that the second time it gets reached it will have a value assigned and PropertyAccess::createPropertyAccessor() will no longer get called.
?? is just a classic isset check meaning the call to createProperyAccesor() is made every time it gets reached.
They're quite different although they look similar.

Collapse
 
saymon profile image
Saymon Tavares

thanks guy!

Collapse
 
bdelespierre profile image
Benjamin Delespierre

Here's another one for you: extract variables from string using patterns

$str = "123:456";

preg_match('/(\d+):(\d+)/', $str, $matches);

list(, $a, $b) = $matches + [null, null, null];

var_dump($a, $b); // 123, 456
Enter fullscreen mode Exit fullscreen mode