Is defining a class method without visibility a shorthand of 'public'?

。_饼干妹妹 提交于 2019-12-10 13:09:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!