dongxixiu9134 2011-02-06 00:20
浏览 53
已采纳

为什么我会使用OOP来隐藏信息?

Why would I use PHP to Hide Information?

<?php

function foo($bar) {
    echo $bar;
}

foo('foobar');

?>

VERSUS

<?php

class foo {
    private $bar;

    function __construct($b){
        $this->bar = $b;
    }

    function display() {
        echo $this->bar;
    }
}

$foobar = new foo('bar');
$foobar->display();

?>
  • 写回答

5条回答 默认 最新

  • dqfsbvd43312 2011-02-06 00:30
    关注

    You would do this to encapsulate the functionality and protect the using code from change. Take this example:

    class Person
    {
        protected $legs;
    
        public function setLegs($number){
             $this->legs = $number;
        }
    }
    

    Lets presume we now have some code that uses this class...

    if ($_POST['legs'])
    {
       $person = new Person;
       $person->setLegs($_POST['legs']);
    }
    

    Ofcours you could do this with the following class

    class Person
    {
       public $legs;
    }
    

    $person = new Person; $person->legs = $_POST['legs'];

    The problem comes if you need to provide any validation to legs or if you want to make changes later. Let's say you have to make a change to the rules about a person (for example the maximum amount of legs a person can have is ten) - if you havent encapsulated the logic you now need to go all over your app finding its uses...

    class Person
    {
        protected $legs;
    
        public function setLegs($number){ 
             if ( ! is_int($number) || $number > 10){
                  throw new Exception('incorrect user input');
             }
             $this->legs = $number;
        }
    }
    

    Encapsulation is important for the following reasons:

    1. It allows application logic to be reused
    2. It makes it possible to make changes easier later
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目