问题
I often see code a function defined without visibility keywords. e.g:
class Foo() {
function bar() {
// ...
}
}
Is it a shorthand of public function? Is it a good practice to omit it?
class Foo() {
public function bar() {
//..
}
}
回答1:
As written in the PHP Doc,
Methods declared without any explicit visibility keyword are defined as public.
So, yes, in
class Foo() { public function bar() { //.. } }
Foo::bar() is public, but omitting the visibility keyword is never a good practice. If it's a fast and ugly script why not, but in other cases you should specify it.
回答2:
Yes, you are right; when you omit the visibility modifier it means it's public.
It's a holdover from PHP 4 which did not support visibility operators. This feature is included for backward compatibility.
You can read more about it here.
来源:https://stackoverflow.com/questions/10987443/is-defining-a-class-method-without-visibility-a-shorthand-of-public