温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP代码编写规范技巧总结

发布时间:2020-05-12 17:04:07 来源:亿速云 阅读:173 作者:Leah 栏目:编程语言

这篇文章为大家带来有关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代码编写规范就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果喜欢这篇文章,不如把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI