我刚刚开始学习面向对象的编程,只是通过观察发现,在所有的例子中,成员变量都是私有的.通常情况如何?
// 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();