douzhenyu6533 2013-03-01 07:18
浏览 38

PHP使用中的私有方法和变量[重复]

This question already has an answer here:

I have been thinking about the usage of private variables and methods in php.

I am not going to talk about a class of car or anything like that. I want to talk about an own script.

What is the difference between using public or private for the programmer and the owner of the script.

if the script is a calculator, and I am the only one who will meinten the code in the future. when do I have to use private variables of methods. How this is going to change anything in the script?

Also, If it's about touching the variable ? if anyone tries to change the value, and he couldn't because of the private thing. He will go directly to change it using the setters ?

I need a good example that I can see private methods or variables have good benefits for programmer or the end user.

I was programming some scripts, and a guy told me to not use var in classes. I asked him why ? he said that you have to use public or private .. and asked why ?

Why to use setter if there is a way to change the variable directly?

Why to use getter if there is a way to change the variable directly?

</div>
  • 写回答

3条回答 默认 最新

  • dtlab08822 2013-03-01 07:27
    关注

    The end user doesn't see the code, so there's no (dis)advantage there.

    For the programmer, declaring things that aren't needed outside the object as private is just a good programming practice and a protection mechanism. Technically, if you're a perfect programmer, and you don't care about how your code looks, using private will provide you no benefits. However, private members enforce the black box model -- you only care about what the object does, not about how it works (when looking at it from the outside). In the end, if for any reason you (or somebody else) needs/wants to use your code, they'll know what methods and properties to use/invoke in order to get the functionality the object has, without modifying the internal values the object needs to maintain. It may or may not give you any advantage -- it's just about how the code looks like. That's what good programming practices are for, and they are usually followed because experience says they tend to minimize errors.

    As for var, it was deprecated. Meaning it could (and will) be removed in the future.

    评论

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂