PHP中3个更好的代码写法

2022-06-17 奥古斯宏

null合并运算符(PHP7)

我们会经常使用isset和empty检查变量或数组中的某个元素,但很多人却写了很多多余的代码,就像这样:

if (isset($_POST['name']) && !empty($_POST['name']))    
    $name = $_POST['name']

上面的代码没有什么问题,但是可以简化为下面的样子:

if (!empty($_POST['name']))    
    $name = $_POST['name']

我们会经常判断null值,一般我们会使用isset和empty,就像上面那样。但我们也有更好、更易读的方法:

$name = $_POST['name'] ?? null

match表达式(PHP8.0)

$class = match ($status) {
    'completed' => 'success',
    'in_progress' => 'warning',
    'failed' => 'danger',
};

在他之前一种典型的用法是这样的:

$class = null;
switch ($status) {
    case 'completed':
        $class = 'success';
        break;
    case 'in_progress':
        $class = 'warning';
        break;
    case 'failed':
        $class = 'danger';
        break;
}

构造器属性提升(PHP8.0)

一个典型的类属性的用法是这样的:

class Customer 
{
    private string $name;
    private string $address;
    private string $phone;
    
    public function __construct(string $name, string $address, string $phone)
    {
        $this->name = $name;
        $this->address = $address;
        $this->phone = $phone;
    }
}

现在可以这样写:

class Customer
{
    public function __construct(
        private string $name,
        private string $address,
        private string $phone
    ) {}
}


版权声明:本文由phpreturn.com(PHP武器库官网)原创和首发,所有权利归phpreturn(PHP武器库)所有,本站允许任何形式的转载/引用文章,但必须同时注明出处。

最近浏览
IP用户:101.67.*.*
1 天前 Generic Bot
IP用户:60.188.*.*
1 天前 Generic Bot
IP用户:66.249.*.*
5 天前 Googlebot
IP用户:54.36.*.*
5 天前 aHrefs Bot
IP用户:72.14.*.*
8 天前 Googlebot
IP用户:220.181.*.*
9 天前 Baidu Spider
IP用户:66.249.*.*
11 天前 Googlebot
IP用户:66.249.*.*
12 天前 Googlebot
IP用户:124.160.*.*
12 天前 Generic Bot
IP用户:220.181.*.*
12 天前 Baidu Spider
IP用户:35.93.*.*
14 天前 Nutch-based Bot
IP用户:66.249.*.*
20 天前 Googlebot
累计浏览次数:966
评论
点击登录
phpreturn,PHP武器库,专注PHP领域的项目和资讯,收录和介绍PHP相关项目。
最近浏览 点击登录
累计浏览次数:101856
一周浏览次数:2870
今日浏览次数:308

本站所有权利归 phpreturn.com 所有

举报/反馈/投稿邮箱:phpreturn@ulthon.com

鲁ICP备19027671号-2