MrZiggyStardust
MrZiggyStardust

Reputation: 733

PHP: Best practice regarding "public" visibility in OOP

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?

Upvotes: 0

Views: 697

Answers (3)

brunoais
brunoais

Reputation: 6836

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

Upvotes: 0

fsw
fsw

Reputation: 3695

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/

Upvotes: 4

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

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

Upvotes: 2

Related Questions