I get a syntax error when I don't declare a member variable as public or private. However if I don't declare a member function as public or private, it defaults to public.
// 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
);
}
}
For the above code, try deleting "private" from the member variables and it won't run, but if you delete 开发者_StackOverflow中文版"public" from the member functions it will run.
From The PHP online manual:
"Class properties must be defined as public, private, or protected."
...and...
"Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public."
[Emphasis mine]
I'm not sure why this is, but it's just the way the language is specified.
You need a keyword before member variables. That keyword used to be var
:
class Foo {
var $bar = null;
function baz() { }
}
var
is to properties as function
is to methods.
var
is deprecated though in favor of explicit visibility declarations. So public
, protected
, private
is to properties as function
is to methods now. Methods additionally take a visibility declaration as well.
Logically they could have chosen public var $bar
as the syntax for properties, but went with a simple public $bar
instead.
精彩评论