当前位置: 首页 > 后端技术 > PHP

PHP代码的简单方法——类和对象部分

时间:2023-03-30 01:16:26 PHP

使用getter和setter在PHP中,可以通过为属性或方法设置public、protected和private关键字来实现对属性或方法的可见性控制。然而,控制可见性也可以通过getter和setter来实现,并且在某些场景下它还有一些额外的好处。使用getters和setters有以下优点:当你想做一些获取对象以外的事情时,你不必去项目中找到所有的属性并修改它,从而更容易添加验证。在获取和设置时添加日志记录和错误处理更方便。我们可以延迟加载类的属性来继承类,并且可以覆盖默认函数。另外,这就是面向对象的基本设计原则中的开闭原则。Bad:classBankAccount{public$balance=1000;}$bankAccount=newBankAccount();//买了一双鞋...$bankAccount->balance-=100;Good:classBankAccount{private$balance;公共函数__construct($balance=1000){$this->balance=$balance;}//做一些事情publicfunctionwithdrawBalance($amount){if($amount>$this->balance){thrownew\Exception('Amount大于可用余额。');}$this->balance-=$amount;}publicfunctiondepositBalance($amount){$this->balance+=$amount;}publicfunctiongetBalance(){return$this->balance;}}$bankAccount=newBankAccount();//买了一双鞋...$bankAccount->withdrawBalance($shoesPrice);//获取余额$balance=$bankAccount->getBalance();让对象拥有私有或受保护的成员Bad:classEmployee{public$name;公共函数__construct($name){$this->name=$name;}}$employee=newEmployee('JohnDoe');echo'员工姓名:'.$employee->name;//员工姓名:JohnDoeGood:classEmployee{private$name;公共函数__construct($name){$this->name=$name;}publicfunctiongetName(){return$this->name;}}$employee=newEmployee('JohnDoe');echo'员工姓名:'.$employee->getName();//员工姓名:JohnDoe用组合代替继承这并不是说不用继承。使用“组合模式”和“继承”有很多很好的理由可以更好地帮助你解决问题。所以,您可能想知道,“我什么时候应该使用继承?”,这取决于手头的问题。下面几点说明什么时候使用继承比较合适。你的继承表达的是等价关系(比如“人是动物”),而不是包含关系(比如“用户有用户的详细信息”)你可以通过修改全局类重用你想要的基类的代码,为所有的派生类修改.坏:类员工{私人$name;私人$电子邮件;公共函数__construct($name,$email){$this->name=$name;$this->email=$email;}//...}//因为员工和税收不是等价关系而是包含关系//所以在这里应用组合更合适classEmployeeTaxDataextendsEmployee{private$ssn;私人$薪水;公共函数__construct($name,$email,$ssn,$salary){parent::__construct($name,$email);$this->ssn=$ssn;$this->薪水=$薪水;}//...}Good:classEmployeeTaxData{private$ssn;私人$工资;公共函数__construct($ssn,$salary){$this->ssn=$ssn;$this->薪水=$薪水;}//...}classEmployee{private$name;私人$电子邮件;私人$税数据;公共函数__construct($name,$email){$this->name=$name;$this->email=$email;}公共函数setTaxData($ssn,$salary){$this->taxData=newEmployeeTaxData($ssn,$salary);}//...}