-4

I've noticed this style of code a lot in frameworks like Symfony and Magento 2 (which is based on Symfony):

<?php
    class Foo
    {
        protected $foo;

        # construct function - not needed for question

        public function getFoo()
        {
            return $this->foo;
        }
    }

Which makes things easier to pick up in terms of get/set/unset but is there any actual advantage over using public vars?

<?php
    class Foo
    {
        public $foo;
    }

It seems the latter has fewer lines but less obvious flexibility.

What are the advantages/disadvantages to each method and when should I use one over the other?

closed as too broad by gnat, Ben Cottrell, BobDalgleish, Greg Burghardt, Jörg W Mittag Jan 8 at 14:02

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

1

With your second version,

class Foo
{
    public $foo;
}

all of the rest of your code can modify $foo.

With the first version:

class Foo
{
    protected $foo;

    # construct function - not needed for question

    public function getFoo()
    {
        return $this->foo;
    }
}

then $foo is protected, so only Foo and classes that inherit from it, can modify $foo. All other code only has access to getFoo, and thus can only read its value.

The "only" advantage is that $foo is no longer publicly modifiable. That advantage can be huge though as it forces the encapsulation of code that modifies it, making the code easier to read and reason about and often makes debugging much simpler too.

Not the answer you're looking for? Browse other questions tagged or ask your own question.