Platzi
Platzi

Suscríbete a Expert y aprende de tecnología al mejor precio anual.

Antes:$249
$209
Currency
Antes:$249
Ahorras:$40
COMIENZA AHORA
1

Explaining public, private and protected variables

As you already know, in OOP there are 3 different types of variables that we can actually use. These are the following:

  • Public
  • Private
  • Protected

The purpose of this article is to explain in a detailed way how this three kinds of variables work and a brief example of how we can use these variables.

Explaining these 3 types of variables/propierties
Let’s discuss each modifier in detail:

  • Private – To access an object’s private members, you need to be inside one of the methods of that object. You can’t access these members while you are inside a method of derived objects. Since you can’t “see” private properties while you’re inside an inheriting class, two different classes can declare identical private properties.
  • Protected – A protected member is similar to a private one in that you can only access it from inside the method of an object. The only difference between these members is that a protected member is visible from an inheriting class. In this kind of situation, you need to use the $this variable to access the protected members.
  • Public – You can access a public member both from inside the object (i.e. using the $this variable) and outside the object (i.e. through $object→Member). These rules will apply if a different class inherits public members. Here, you can access the members both from inside the class’s methods and outside its objects.

Programmers use the “public” modifier for member variables that they need to access from outside the methods of an object. These people use “private” for variables that must be kept inside the logic of an object. Lastly, they use the “protected” modifier for variables that are placed inside an object, but will be passed on to inheriting classes. The following example will illustrate these ideas:

classYourDatabaseConnection{
public $searchResult;
protected $databaseHostname = “127.0.0.1”;
private $connectionID;
// This is an example.
}
classMyDatabaseConnectionextendsYourDatabaseConnection{
protected $databaseHostname = “192.168.1.1”;

This example, although incomplete, shows the proper usage of each access modifier. Basically, the class involved handles database connections (e.g. database queries):

  • The system stores the connection ID inside a “private” data member. That’s because only the internal logic of the class needs access to this information.
  • Here, the user of the YourDatabaseConnection class cannot see the database’s hostname. The programmer may override this by inheriting the data from the original class and altering the assigned value.
  • The user needs to access the result of his/her search. Thus, $searchResult must be a “public” variable.
Escribe tu comentario
+ 2