站长资讯网
最全最丰富的资讯网站

PHP代码编写规范

不添加不需要的上下文

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

差:

<?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教程》

赞(0)
分享到: 更多 (0)