0
votes

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?

3
I don't think it really makes any difference - personal preference. The key thing is to be consistent.Mansfield
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

3 Answers

4
votes

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/

2
votes

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

0
votes

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