by Dinesh Thakur

The visibility of the properties and methods of an object is one of the basic features of object-oriented programming. This tutorial aims to introduce different levels of visibility offered by the object model PHP 5. We will review them one by one through practical examples and we will bring some good practices to adopt when used.

What is the visibility of the properties and methods of an object?

The visibility defines how an attribute or method of an object will be accessible in the program. Such as Java, C ++, or ActionScript 3, PHP introduced 3 different levels of visibility apply to properties or methods of the object.

These visibilities public, private, or protected, which are respectively defined in the class using the keywords public, private, and protected.

The following example illustrates the syntax of data reporting members (attributes) and methods with different visibilities. We will explain just after each particularity visibility levels.

Use keywords public, private, and protected

<?php
     class Vehicle
     {
          // Attributes
               public $mark;
               private $FuelVolume ;
               protected $isRepare;

          // Methods
               public function construct ()
                 {
                     $this -> FuelVolume = 40;
                     $this -> isRepare = false;
                 }

         // Start the car if the tank
        // Is not empty
             public function Start ()
               {
                   if ($this -> FuelVolumeControler ())
                       {
                           echo 'The vehicle starts';
                                     return true;
                       }

                           echo 'The tank is empty ...';
                                     return false;
               }

                  // Check if there's fuel in the tank
                       private function FuelVolumeControler ()
                           {
                                return ($this -> FuelVolume> 0); // Returns true or false
                           }

                // Set the vehicle maintenance
                       protected function repair ()
                           {
                                 $this -> isRepare = true;
                                     echo 'The vehicle is in repair';
                           }
     }

We note here that we were already using attributes and public methods in the examples of the first tutorial on object oriented programming. Now present each of visibility levels.

Public access

This is the PHP default access if one says no visibility. All attributes and methods that are declared without any of these three keywords will automatically be considered by the public as interpreter.

The public keyword indicates that the properties and methods of an object will be accessible from anywhere in the main program or in the inherited or derived subclasses parent classes. Remember these words in a corner of your memory as we present the concepts of inheritance to the next tutorial.

Concretely, this is what we did in the previous tutorial. What gives with our example:

Using public visibility

<?php
    // Instantiation of the object: implicit call to the construct () method
     $MyVehicle = new Vehicle();

    // Update the vehicle brand
     $MyVehicle-> mark = 'Honda';

    // Display the vehicle brand
         echo $MyVehicle -> mark;
?>

In this example, we see that we can directly read and change the value of the brand in the public attribute directly calling this way: $ MyVehicle-> mark (without dollars).

We will see just after the same usage will be impossible with private and protected attributes.

Note: when you instantiate the class to create a new object, the keyword "new" charge to call the class constructor method. The latter must necessarily be declared public because it is called from outside the class.

The private access

The private keyword is used to declare attributes and methods that will be visible and accessible directly from within that same class. That is, it becomes impossible to read or write the value of an attribute directly by private $MyVehicle -> FuelVolume. Also to use FuelVolumeControler () method via $MyVehicle -> FuelVolumeControler (). You will notice testing, a fatal error is generated at runtime.

The value of the private attribute $ FuelVolume is initialized in the class constructor. That is, when constructing the object.

For example, when our vehicle is finally assembled and ready for use, it will be sold to the customer with the fuel tank filled or 40L.

A method is declared private when it is not intended to be used outside of the classroom. Private methods are used in particular to validate data in an object or to perform various internal treatments. This is for example the task that fills the private method FuelVolumeControler () when called by the public method Start (). This private method verifies that there's much of the fuel in the vehicle by testing the value of the private attribute $ FuelVolume. If this is the case, the method returns true and so the car starts. Otherwise, the return value is FALSE and the car will not start.

Call the START () method on the subject $MyVehicle
<?php

     // Displays: "The vehicle starts"
      $MyVehicle-> Start ();

?>

Access protected

The protected access (protected) is an intermediary between public access and private access. It allows the use of common attributes and methods in a parent class and derived classes.

However, we have to anticipate it to understand how the protected access. For this, we will add a Car class that will inherit our current class Vehicle. As a car is a kind of vehicle it is possible we derive the class Vehicle with a Car class.

The Vehicle class will contain the attributes and methods common to any type of vehicle while the car class will encapsulate the properties and methods specific to cars. For example, the brand or boolean isRepare may well be shared attributes. Against by the volume of fuel in the tank is not common to all vehicles.

Indeed, a bike, a scooter or even a rowing can be considered non-motorized vehicles. They therefore have no tank and do not work with fuel.

Using protected access
<?php

      class Vehicle
         {
                // Attributes
                     protected $Trademark;
                     protected $istRepare;

                // Methods
                     public function construct ($name)
                        {
                            $this -> brand = $trademark;
                            $this -> isRepare = false;
                        }

                // Set the vehicle maintenance
                     public function repair ()
                        {
                            $this -> isRepare = true;
                            echo 'The vehicle is in repair';
                        }
          }
     Car class extends Vehicle
         {
               // Attributes
                    private $FuelVolume ;

              // Constructor
                   public function construct ($name)
                      {
                          // Call the constructor of the parent class
                               parent ::construct ($name);
                           $this -> FuelVolume = 40;
                      }

            // Start the car if the tank
            // Is not empty
                 public function Start ()
                     {
                          if ($this -> FuelVolumeControler ())
                              {
                                  echo 'The vehicle starts';
                                  return true;
                              }

                                  echo 'The tank is empty ...';
                                  return false;
                      }

                   // Check that there's fuel in the tank
                        private function FuelVolumeControler ()
                            {
                                 return ($this -> FuelVolume> 0);
                            }
            }

We just declare protected two attributes in the parent class Vehicle and we descended the FuelVolume attribute in the car class. Similarly we back down methods Start() and FuelVolumeControler () in the car class. Thus, we can now instantiate a new object of type Car and enjoy the attributes and methods of the Vehicle class and more. Finally, note that the repair () method is passed from the public protected mode in order to call from outside the class. Which give :

Use of protected attributes and methods
<?php

      $MyVehicle = new Car ('Honda');
      $MyVehicle-> Start ();
      $MyVehicle-> repair ();

?>

Updating a private or protected attribute: role of mutator

We mentioned earlier that it was impossible to access the value of an attribute or private protected using the following syntax: $object-> attribute. A fatal error is generated. How to update the value of the attribute in this case? This is where the mutator.

The mutator is neither more nor months that a public method to which the new value to assign to the attribute we pass as a parameter. By convention, these methods are called with the set prefix. For example: setBrand (), setFuelVolume () ... This is why you will hear most often mention setter that mutator.

Add a mutator to our Car class that changes the value of the fuel volume. This gives:

Added mutator (setter) setFuelVolume to Class Car
<?php

     Car class extends Vehicle
         {

                 // ...

                 public function setFuelVolume ($dVolume)
                     {
                        $this -> FuelVolume = $dVolume;
                     }
         }

To meet the IT development conventions we use in our example writing using the set prefix. But this name is completely arbitrary and our method might well have to call doFull() or FillTank (). It takes that to you to give meaningful names to your methods.

As for the use of this method, it is simply a traditional method call.

Update the value of the private attribute $ FuelVolume
<?php

     // I fill my 50 L fuel tank
      $MyVehicle-> setFuelVolume (50);
?>

Get the value of a private or protected attribute: role of accessor

We have just studied how to update (write) the value of an attribute private or protected. It only remains for us that to address the case of reading that value. How this value is restored in a program knowing that direct access to the attribute is forbidden? In the same way as the mutator, we should declare a method that will be responsible to return the value of the attribute. It is neither more nor less than a function with a return statement.

We call such a method accessor or more commonly a getter. Indeed, by convention, these methods are prefixed the word get. Just as the mutators, it is possible to apply any name a accessor.

Returning to our previous example. The getter below explains the principle of returning the value of a private attribute. We refer here the value of the variable $ FuelVolume.

Declaring an accessor for private attribute $ FuelVolume Class Car
<?php

     Car class extends Vehicle
       {
           // ...

           public function getFuelVolume ()
               {
                   return $this -> FuelVolume;
               }
        }

Here's an example of using the method getFuelVolume :

Using the get accessor FuelVolume() on the object $MyVehicle
<? php

     echo sprintf ("% u It remains The essence of" $MyVehicle-> getFuelVolume ());

?>

That's all there is to know about the visibility of essential methods and attributes as well as the access to the values ​​of the latter. Before concluding this tutorial, do a short reminder of good object-oriented development practices history that you can immediately start with a solid foundation.