php编写代码规范,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教程》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值