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 code that Iβve encountered and introduce a commented solution if needed, as you know there are 4242424242424 ways to do the same thing β¨ and Itβs OK to disagree with my solution π
π For my examples I use PHP 7.4
π π₯
1 - In this use case, just return the expression π
if($foo === 42) {
return true;
}
return false;
// can be
return $foo === 42;
2 - Null coalescing operator for the win π
if($foo !== null) {
return $foo;
}
return $bar;
// can be
return $foo ?? $bar;
π‘ Itβs very handy to avoid exceptions when you want to access a key that doesnβt exist
3 - Straight to the point π₯
$this->user = ['firstname' => 'smaine', 'mail' => 'contact@smaine.me'];
return $this->user;
// can be
return $this->user = ['firstname' => 'smaine', 'mail' => 'contact@smaine.me'];
4 - Initialize your helper once π
class FooTransformer
{
private $propertyAccessor;
public function transform(array $data): Foo
{
$accessor = $this->getAccessor();
// stuff
}
private function getAccessor(): PropertyAccess
{
return $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor(); // @lito
}
}
5 - Unpack an array π©
$users = [
['smaone', 'php'],
['baptounet', 'javascript'],
];
foreach($users as [$username, $language]) {
// $username contains the 1st key "smaone" for the 1st iteration
// $language contains the 2nd key "php" for the 1st iteration
}
In the same way, we can also assign variables from an array, it is useful if a function returns an array π
function getFullname(int $id): array
{
$statement = $pdo->prepare("SELECT id, lastname, firstname FROM user WHERE id = ?");
$statement->execute([$id]);
$result = $statement->fetch();
// suppose $result contains [42, 'luke', 'lucky'];
return $result;
}
// main.php
[$id, $lastname, $firstname] = getFullname(42);
// $id contains 42
// $lastname contains luke
// $firstname contains lucky
I hope you enjoyed the read!
Feel free to follow me on GitHub, LinkedIn and DEV for more!
Top comments (4)
Is same as:
??= 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.
thanks guy!
Here's another one for you: extract variables from string using patterns