Answer the question
In order to leave comments, you need to log in
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:
Answer the question
In order to leave comments, you need to log in
what is the use of public in a real example?Well look.
// класс для работы с mysql
class Database
{
/**
* Ресурс соединения с mysql
* @var mysqli
*/
public $connection;
public function __construct()
{
$this->connection = mysqli_connect(/**/);
}
}
$db = new Database();
// какой-то петя в коде написал случайно:
$db->connection = 123; // все сломалось
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
class Foo
{
public Quux $quux;
}
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question