【发布时间】:2011-10-15 11:44:20
【问题描述】:
我今天刚开始学习面向对象编程,只是通过观察发现在所有示例中,成员变量都是私有的。为什么通常是这样?
// 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,那么在声明它的类之外访问它的语法是什么?
最后,你必须在类中的每个变量和函数前面加上“public”或“private”吗?
编辑:感谢大家的回答,谁能确认您是否必须在类中的每个变量和函数前面加上“公共”或“私有”?
谢谢!
【问题讨论】:
-
听起来你需要读一本关于面向对象编程的书。你问了一些关于面向对象编程基础的非常好的、直接的问题。我没有足够的时间来获得完整的答案,所以我只会说查找
Encapsulation、Inheritance和Abstraction。