1.返回表达式

<?php
if($foo === 42) {
     return true;
 }
return false;

// can be
return $foo === 42;

2.Null合并运算符

<?php
if($foo !== null) {
  return $foo;
}
return $bar;

return $foo ?? $bar;

3.当你想访问一个不存在的key时避免异常时


<?php
$username = null;
if(isset($data['user']['username'])) {
    $username = $data['user']['username'];   
}

// can be
$username = $data['user']['username'] ?? null;

4.method_exist尽可能避免使用接口


<?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.使代码富有表现力


<?php
class FooService
{
  //
  if($this->isLoggable($object)) {
    $object->setUpdatedAt();
  }
  //

 public function isLoggable($object): bool
 {
   return $object instanceof LoggableInterface;
 }
}

6.切入正题

<?php
$this->user = ['firstname' => 'smaine', 'mail' => 'contact@smaine.me'];

return $this->user;

// can be
return $this->user = ['firstname' => 'smaine', 'mail' => 'contact@smaine.me'];

7.初始化一次helper


<?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.解包数组


<?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.从数组中赋值(如果函数返回一个数组就很有用)


<?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 接受几个参数


<?php

if (isset([$_GET['id']) && isset([$_GET['limit'])) {
  // stuff
}

// can be 
if (isset($_GET['id'], $_GET['limit']) {
  // stuff 
}

unset($user, $product) 和 var_dump($data, 42, $users)都是可以的

点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部