php – 为什么成员变量通常是私有的?

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

// 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”?

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

谢谢!

解决方法:

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

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

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...