dqnqpqv3841 2010-09-04 23:08
浏览 98
已采纳

PHP:封装的目的是什么?

I'm talking specifically about the public, private and protected keywords that can apply to properties and methods. I've looked everywhere and I know what they do and how to use them, but don't see how they would be practical when programming. Could somebody explain or give an example?

  • 写回答

4条回答 默认 最新

  • dongshi3061 2010-09-04 23:15
    关注

    The primary purpose of encapsulation (scope) is to ensure that you write code that can't be broken. This applies to scope in general, so let me use a simpler example of a local variable inside a function:

    function xyz ($x) {
      $y = 1;
      while ($y <= 10) {
        $array[] = $y * $x;
        $y++;
      }
      return $array;
    }
    

    The purpose of this function is to pass a number and return an array. The example code is pretty basic. In order for function xyz() to be dependable, you need to be guaranteed that it does the exact same thing every time. So what if someone had the ability to from the outside change that initial value of $y or $array? Or even $x? If you were able to do that from outside of the function, you could no longer guarantee what that function is returning.

    That is where scope (encapsulation) comes into play. It is a way of setting boundaries, of assigning permissions of what can and can't be done with your variables (and functions, properties, methods, objects) to make sure that bit of code will always do exactly what it is expected to do.

    Take for instance any built-in php function like...strtolower() or preg_match() or ...well anything. They expect arguments to be passed to them, and they return something specific. Internally there are variables, loops, etc... to take the input and spit out an output. If you were to be able to change that stuff from the outside, there would be no way to guarantee that strotolower() will return a lowercased string you feed it, and that defeats the purpose of having a reusable code block.

    This isn't necessarily all that useful when you are programming for yourself, but when you are writing code to be used and shared by many people, especially with using code that involves addons/plugins, etc... it is invaluable for ensuring your code does what it is supposed to be doing, and is accessed/used/called in an expected way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP