为什么成员变量通常是私有的?(Why are member variables usually private?)

编程入门 行业动态 更新时间:2024-10-28 01:20:49
为什么成员变量通常是私有的?(Why are member variables usually private?)

我刚刚开始学习面向对象编程,只是通过观察发现,在所有示例中,成员变量都是私有的。 通常情况如何?

// Class class Building { // Object variables/properties private $number_of_floors = 5; // These buildings have 5 floors private $color; // Class constructor public function __construct($paint) { $this->color = $paint; } public function describe() { printf('This building has %d floors. It is %s in color.', $this->number_of_floors, $this->color ); } }

此外,如果您声明成员变量是公共的,那么在声明它的类之外访问它的语法是什么?

最后,你是否必须在类中的每个变量和函数前加上“public”或“private”?

编辑:谢谢大家的答案,任何人都可以确认你是否必须在课堂上的每个变量和功能前加上“公共”或“私人”?

谢谢!

I just started to learn object oriented programming today and just by observation noticed that in all examples, member variables are private. Why is that usually the case?

// Class class Building { // Object variables/properties private $number_of_floors = 5; // These buildings have 5 floors private $color; // Class constructor public function __construct($paint) { $this->color = $paint; } public function describe() { printf('This building has %d floors. It is %s in color.', $this->number_of_floors, $this->color ); } }

Also, if you declare the member variable to be public, what is the syntax for accessing it outside of the class it was declared in?

And finally, do you have to prepend "public" or "private" to every variable and function inside a class?

EDIT: Thanks all for your answers, can anyone please confirm if you have to prepend "public" or "private" to every variable and function inside a class?

Thanks!

最满意答案

无法从外部访问私有变量,这使您可以控制。

但是,如果你把它们公开,那么你可以访问它

$your_object_instance->Your_variable

例如

$building = new Building(); echo $building->number_of_floors;

但是你必须把你的number_of_floors变量公开,如果你想访问私有成员那么你需要在Building类中实现新方法

public function getNumberOfFloors() { return $this->number_of_floors; }

所以你的代码应该是这样的

$building = new Building(); echo $building->getNumberofFloors();

Private variables can't be accessed from outside, that gives you control.

But if you put them Public then you can access it lke this

$your_object_instance->Your_variable

For example

$building = new Building(); echo $building->number_of_floors;

but you have to put your number_of_floors variable to public, if you want to access private member then you need to implement new method in Building class

public function getNumberOfFloors() { return $this->number_of_floors; }

so your code should look like this

$building = new Building(); echo $building->getNumberofFloors();

更多推荐

本文发布于:2023-04-27 12:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326120.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   成员   member   variables   private

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!