duandou2763 2017-04-19 10:54
浏览 27

getter和setter如何在PHP中工作[重复]

This question already has an answer here:

I need to know how getter and setter will work in PHP. Because some interviewer asked tricky question about getter and setter. I have failed to explain. Can any one help me out?

</div>
  • 写回答

1条回答 默认 最新

  • donglu5612 2017-04-19 11:09
    关注

    Getters and setters are used to- at a later stage- make it possible to provide logic when the developer requests or sets a variable.

    If you, for example, want to add a layer of validation to prevent your object from being misused. What if you wanted to make sure that the person’s $name variable is a string variable and not something else? Well, we can simply add that layer of validation to our setter method:

    //Set the person's name.
    public function setName($name){
       if(!is_string($name)){
           throw new Exception('$name must be a string!');
       }
       $this->name = $name;
    }
    

    In the PHP code above, we modified the setter method setName so that it validates the $name variable. Now, if a programmer attempts to set the $name variable to an array or a boolean, our function will throw an Exception. If we wanted to, we could also make sure that the $name variable is not a blank string.

    Big thanks to this post.

    Best of luck on your interview!

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度