Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

visibility

php

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() {
    //..
  }
}
like image 997
gilzero Avatar asked Jun 11 '12 20:06

gilzero


2 Answers

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.

like image 22
korko Avatar answered Sep 27 '22 23:09

korko


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.

like image 111
Viacheslav Kondratiuk Avatar answered Sep 27 '22 21:09

Viacheslav Kondratiuk