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