1. Return expression
<?php
if($foo === 42) {
return true;
}
return false;
// can be
return $foo === 42;
2.Null merge operator
<?php
if($foo !== null) {
return $foo;
}
return $bar;
return $foo ?? $bar;
3. Avoid exceptions when you want to access a key that does not exist
<?php
$username = null;
if(isset($data['user']['username'])) {
$username = $data['user']['username'];
}
// can be
$username = $data['user']['username'] ?? null;
4. method_exist
avoid using interfaces as much as possible
<?php
class FooService
{
//
if(method_exist($user,'setUpdatedAt') {
$object->setUpdatedAt();
}
// use interface
interface LoggableInterface
{
public function setUpdatedAt();
}
class FooService
{
//
if($object instanceof LoggableInterface) {
$object->setUpdatedAt();
}
}
5. Make the code expressive
<?php
class FooService
{
//
if($this->isLoggable($object)) {
$object->setUpdatedAt();
}
//
public function isLoggable($object): bool
{
return $object instanceof LoggableInterface;
}
}
6. Get to the point
<?php
$this->user = ['firstname' =>'smaine','mail' =>'contact@smaine.me'];
return $this->user;
// can be
return $this->user = ['firstname' =>'smaine','mail' =>'contact@smaine.me'];
7. Initialize the helper once
<?php
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();
}
}
8. Unpack the array
<?php
$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
}
9. Assign values from an array (useful if the function returns an array)
<?php
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
10.isset
unset
var_dump
accepts several parameters
<?php
if (isset([$_GET['id']) && isset([$_GET['limit'])) {
// stuff
}
// can be
if (isset($_GET['id'], $_GET['limit']) {
// stuff
}
unset($user, $product) and var_dump($data, 42, $users) are both possible
Post comment 取消回复