不添加不需要的上下文

如果你的类名或对象名称有具体的含义,请不要重复该变量的名称。

差:

<?php class Car{    public $carMake;    public $carModel;    public $carColor;    //...    }

好:

<?php class Car{    public $make;    public $model;    public $color;    //...    }

函数参数数量(理想情况是 2 个以下)

限制函数参数的数量是非常重要的,因为它让函数更容易测试,参数超过三个的话,你必须用每个单独的参数测试大量不同的情况。

无参数是理想的情况。一个或两个参数是可以的,但应该避免三个。通常,如果你有两个以上的参数,那么你的函数试图完成太多的功能,若不是,大多数时候,较高级的对象就足以作为参数(译者注:比如数组、对象)。

差:

<?php function createMenu($title, $body, $buttonText, $cancellable) {    // ...}

好:

<?php class MenuConfig {    public $title;    public $body;    public $buttonText;    public $cancellable = false;}$config = new MenuConfig();$config->title = 'Foo';$config->body = 'Bar';$config->buttonText = 'Baz';$config->cancellable = true;function createMenu(MenuConfig $config) {    // ...}

一个函数应该只完成一件事

这是软件工程中最重要的规则。当函数做的事多于一件事情时,他们更难编写和测试。 当你可以将函数隔离成一个动作时,可以轻松重构,代码也将更易读。

差:

<?phpfunction emailClients($clients) {    foreach ($clients as $client) {        $clientRecord = $db->find($client);        if ($clientRecord->isActive()) {            email($client);        }    }}

好:

function emailClients($clients) {    $activeClients = activeClients($clients);    array_walk($activeClients, 'email');}function activeClients($clients) {    return array_filter($clients, 'isClientActive');}function isClientActive($client) {    $clientRecord = $db->find($client);    return $clientRecord->isActive();}

使用 get 和 set 方法

在 PHP 中,可以为方法设置 public、protected 和 private 关键字,可以控制对象上的属性可见性。这是面向对象的设计原则中的开放/封闭原则的一部分。

差:

class BankAccount{    public $balance = 1000;}$bankAccount = new BankAccount();// Buy shoes...$bankAccount->balance -= 100;

好:

class BankAccount{    private $balance;    public function __construct($balance = 1000)    {      $this->balance = $balance;    }    public function withdrawBalance($amount)    {        if ($amount > $this->balance) {            throw new \Exception('Amount greater than available balance.');        }        $this->balance -= $amount;    }    public function depositBalance($amount)    {        $this->balance += $amount;    }    public function getBalance()    {        return $this->balance;    }}$bankAccount = new BankAccount();// Buy shoes...$bankAccount->withdrawBalance($shoesPrice);// Get balance$balance = $bankAccount->getBalance();

推荐教程:《PHP教程》

更多相关文章

  1. PHP中100个最常用的函数
  2. PHP使用Composer进行注册全局函数
  3. 【 callable-fake】虚构你的可调用函数以加速测试
  4. PHP中的危险函数你知道吗?
  5. PHP中的面向对象之构造函数详解
  6. php面向对象之析构函数和对象引用
  7. 构造函数在php中的使用方法(附示例)
  8. php中函数参数传递的3种方式和区别(附详解)
  9. php中Date函数和时间戳函数及它们之间格式转换教程(附实例)

随机推荐

  1. 这一年我都做了些什么?
  2. WIN10从休眠中唤醒,总是要点“登录”才能
  3. Python排序傻傻分不清?一文看透sorted与so
  4. 用Python实现跳一跳自动跳跃。
  5. 2018年原创精选文章汇总
  6. OpenCV:目标跟踪。
  7. 自然语言处理中句子相似度计算的几种方法
  8. 4、输入、输出重定向、管道符、Vim编辑器
  9. 一言不合就改成 777 权限?会出人命的!
  10. 干货 | SQL如何学?分享5大免费学习资源