0

Do you always add public beside methods and properties inside your classes? Or do you leave it out?

1. Option 1, without public:

<?php
class SimpleClass {
    // property declaration
    $var = 'a default value';

    // method declaration
    function displayVar() {
        echo $this->var;
    }
}
?>

2. Option 2, with public:

<?php
class SimpleClass {
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

Personally I think adding public adds a little more clarity to the code, though what is considered best practice?

MrZiggyStardust
  • 713
  • 6
  • 19
  • I don't think it really makes any difference - personal preference. The key thing is to be consistent. – Mansfield Apr 25 '13 at 09:53
  • Yes, if you don't want to follow a standard. It comes down to personal preference I guess. I am going to stick to always adding public :) – MrZiggyStardust Apr 25 '13 at 10:59

3 Answers3

4

Best practice is to pick up a coding standard and follow it (and put info about it somewhere in your code).

I guess PSR is most commonly used in PHP:

https://github.com/php-fig/fig-standards/tree/master/accepted

and according to PSR-2:

"Visibility MUST be declared on all properties."

so second option would be a way to go.

you can also check this:

http://www.phptherightway.com/

fsw
  • 3,595
  • 3
  • 20
  • 34
2

Second approach is considered as best practice, because it creates readability for any user.

Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
0

Just about always specify the the value even if it's the default.

brunoais
  • 6,258
  • 8
  • 39
  • 59