没有增加没有需求的上下文
假如你的类名或工具称号有详细的含意,请没有要反复该变量的称号。
差:
<?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教程》
以上就是PHP代码编写标准的具体内容,更多请存眷资源魔其它相干文章!
标签: php php开发教程 php开发资料 php开发自学
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!