PHP 代码简洁之道——对象部分

教程 shanhuhai 3495℃ 0评论

(译者注:以下两点主要是说不要直接操作对象的属性,而是通过方法来间接操作,这样可以封装类的内部细节,避免对象内部属性被意外修改)

1.使用 setter 和 getter

在 PHP 中,你可以为方法设置 public, protectedprivate 关键字。使用这些关键字你可以控制一个对象的属性修改权限。

  • 如果除了获取对象属性你还想做一些别的事,就不用再到代码库中去寻找并修改每一个修改对象属性的地方(属性入口归一)。
  • 方便数据验证
  • 封装内部实现
  • 获取和设置时方便添加日志和错误处理
  • 继承了类,你可以重写默认的函数
  • 我们可以延迟加载类的属性,假设它是从服务器获取的

另外,这是开放/封闭原则的一部分,是面向对象的基本设计原则。

不好的


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();

2.让对象有 私有(private)/受保护的(protected) 的成员

不好的


class Employee { public $name; public function __construct($name) { $this->name = $name; } } $employee = new Employee('John Doe'); echo 'Employee name: '.$employee->name; // Employee name: John Doe

好的

class Employee
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

$employee = new Employee('John Doe');
echo 'Employee name: '.$employee->getName(); // Employee name: John Doe

转载请注明:大后端 » PHP 代码简洁之道——对象部分

付费咨询
喜欢 (8)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址