-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?

treyBake
  • 95
  • 3
  • 1
    see [What is the problem with “Pros and Cons”?](https://softwareengineering.meta.stackexchange.com/q/6758/31260) – gnat Jan 07 '19 at 12:16
  • @gnat ah I see :S how would you advise an edit to make it more applicable to here? :) – treyBake Jan 07 '19 at 12:17
  • And while a bit off topic, Magento uses several Symfony libraries [(console event dispatcher and process)](https://symfony.com/projects/magento). It is not based on the Symfony framework. – Cerad Jan 07 '19 at 21:55
  • 1
    Possible duplicate of [When are Getters and Setters Justified](https://softwareengineering.stackexchange.com/questions/21802/when-are-getters-and-setters-justified) – outis Jan 08 '19 at 05:48

1 Answers1

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.

David Arno
  • 38,972
  • 9
  • 88
  • 121