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

查看:480
本文介绍了为什么成员变量通常是私有的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天才开始学习面向对象的编程,并且通过观察发现,在所有示例中,成员变量都是私有的.为什么通常会这样?

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?

最后,您是否必须在类中的每个变量和函数之前添加"public"或"private"?

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

谢谢大家的回答,任何人都可以确认是否必须对类中的每个变量和函数添加"public"或"private"吗?

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?

谢谢!

推荐答案

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

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

例如

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

但是您必须将number_of_floors变量公开,如果要访问私有成员,则需要在Building类中实现新方法

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();

这篇关于为什么成员变量通常是私有的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆