D
D
DVP882020-04-30 17:26:46
PHP
DVP88, 2020-04-30 17:26:46

What is the danger of using the public modifier?

Greetings, tell me, please, I can’t figure out how to use public , protected and private access modifiers, their purpose is clear to me in which case and what to use too, but what is the use of public in a real example ? The maximum explanation is very succinct and it is not clear where the real practical problem lies, other than the abstract representation of the error:

Third party explanation

Это плохо по нескольким причинам:
  • Если поле можно изменить в любом месте программы, сложно отслеживать ошибки, потому что не всегда понятно, где что-то пошло не так.
  • Если вдруг в программу во время работы попадёт чужой код, он сможет изменять и читать любые поля любых объектов.

Источник: статья "ООП. Часть 3. Модификаторы доступа, инкапсуляция", не знаю, можно ли озвучивать с какого сайта

PHP 7.4 introduced type hint, and a couple of English-language resources state that the __get and __set magic methods are no longer required, because now we can not be afraid that incorrect data will be entered. Is it so? How is it really worth using access modifiers and influencing variables, taking into account the type hint?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Northern Lights, 2020-05-01
@DVP88

what is the use of public in a real example?
Well look.
Imagine that you are an object, and all your properties (heart, liver, stomach) are public. I can come up to you, poke a finger in your heart and you will die. Similarly, in objects, those properties that are responsible for the health of the class object, which should not be accessible from the outside, are made private / protected.
How to place food in closed properties (stomach)? Let's make a public EAT() method that will put food there. We serve food at the entrance.
Why do we need a method if, theoretically, the stomach could be made public and put food into it directly, with a shovel? Obviously, the IS() method has some input validation. For example, if you put rotten meat in your mouth, then this "food" simply will not go further - the gag reflex will work.
The same analogy with programming - good practice - to do the so-called. setters/getters are methods that accept and return properties of objects. Some logic can be applied to these methods. For example, when setting a property, check its correctness, and when returning, return it in a certain format.
When are public properties needed? In very rare cases, for example when an object acts as a kind of storage, for example, \stdClass is a PHP top-level object. But in real development, these are very rare occurrences.
All classes must have private properties and getters/setters to manipulate them. This is good practice.
Well, a simple example:
// класс для работы с mysql
class Database
{
    /**
     * Ресурс соединения с mysql 
     * @var mysqli
     */
    public $connection;

    public function __construct()
    {
        $this->connection = mysqli_connect(/**/);
    }
}

$db = new Database();

// какой-то петя в коде написал случайно:
$db->connection = 123; // все сломалось

B
bkosun, 2020-04-30
@bkosun

Simple example:

class Foo
{
  public $quux;
}

class Bar
{
  private $quux;

  public function setQuux(Quux $quux)
  {
    $this->quux = $quux;
  }
}

class Quux
{
}

$foo = new Foo();
$foo->quux = 'text';  // Work

$foo = new Bar();
$foo->quux = 'text'; // Member has private access

The quux property is a public property of the Foo class. With this approach, you can manipulate it as you like and store any data there.
With the advent of typed properties (PHP 7.4) - you can not use setters:
class Foo
{
  public Quux $quux;
}

What if there is a property in the class that should not be changed? The idea is that the class should provide an API for working with it, in order to exclude the possibility of breaking the logic of its work.
Closing the API allows design flaws to be found more easily and gives you the opportunity to evolve your code by creating well defined extension points.

fabien.potencier.org/pragmatism-over-theory-protec...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question