This content originally appeared on DEV Community and was authored by Saymon
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 ?? $this->propertyAccessor = PropertyAccess::createPropertyAccessor();
}
}
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!
This content originally appeared on DEV Community and was authored by Saymon
Saymon | Sciencx (2021-08-24T20:17:58+00:00) 5 tips in PHP ?. Retrieved from https://www.scien.cx/2021/08/24/5-tips-in-php-%f0%9f%90%98/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.