Property Hiding

Property hiding in PHP (or I guess in any other language which supports an object model as well) is massively used and its idea is almost absolutely self-explanatory. However, since I started my series some time ago, I’ll go through it as well. It is mainly the basis of my future tutorials from the series which would include some of the most commonly used templates in PHP. So let’s begin with our examples.

Let’s take this class for instance (Calories.php):

<?php  

class Calories{  

     public $age;  
     public $gender;  

}  

?>  

Suppose the purpose of the class is to calculate the amount of calories of a person based on his age and gender (no quite original but that’s what I managed to come up with). Now these properties are public which automatically means that if we happen to have an instance of the class Calories, everyone from outside can access it. Let’s go to index.php where our instance is.

<?php  

include 'Calories.php';  
$a=new Calories();  
$a->age=200;  

?>  

That is just how one would go about for accessing it and inserting arbitrary data. But a worse scenario would be if the guy was to define a boolean value.

<?php  

include 'Calories.php';  
$a=new Calories();  
$a->gender=true;  

?>  

We certainly do not want that to happen as it will mess up our code immensely. So we have one property which we have to assign and subsequently to be able to use it. The idea is that if it is public, we cannot validate the data being submitted/inputted. One of the things we could do in this case is to validate that through a constructor.

<?php  

class Calories{  

     public $age;  
     public $gender;  

     public function __construct() {  

     }  
}  

?>  

It will, logically, accept a few parameters (in our case - age and gender) and to validate them within it. But suppose we want those values to be dynamically altered. Yeah we could simply make an instance but when we pass them through the constructor and make the properties as a private (or protected, depends on the situation) visibility so that they cannot be accessed from outside. But then when/if we want to assign a new value to them we would need to make a new instance of the class again which is not practical because we may have some other data that is already been used and so on.

So here comes the actual property hiding concept also known as Getters & Setters.

<?php  

class Calories{  

     public $age;  
     public $gender;  

     public function __construct() {  

     }  


     public function getAge() {  
          return $this->age;  
     }  

     public function setAge() {  
          $this->age = $age;  
     }  

     public function getGender() {  
          return $this->gender;  
     }  

     public function setGender() {  
          $this->gender = $gender;  
     }  

}  

?>  

Those are methods that grant public visibility/access over hidden properties. Now some environments and IDEs like NetBeans offer automatic writing of such methods with ALT + INSERT but it’s for laziness. Just to know it.

So we have private properties but public methods that would return it (speaking of the getters). And because of the method being in the class, we can call private properties and return them as well. But in case of setting a value, we have the method setAge() with one parameter (age) which appends that parameter to the private property.

<?php  

include 'Calories.php';  
$a=new Calories();  
$a->setAge(11);  

?>  

Now in our index.php we can set the age value to let’s say 11 but we don’t have access to the actual property. So we can simply make a loop for a check that would append the value being submitted if it passes the check. So now we can indeed validate the in coming data.

<?php  

class Calories{  

     private $age;  
     private $gender;  

     public function __construct() {  

     }  


     public function getAge() {  
          return $this->age;  
     }  

     public function setAge() {  
         if($age<55) {  
            $this->age = $age;  
         }  
     }  

     public function getGender() {  
          return $this->gender;  
     }  

     public function setGender() {  
          $this->gender = $gender;  
     }  

}  

?>  

In that way we have a private property which is in the scope of the class but it becomes publicly accessible and in those loops we can modify, check and whatever we want to validate in the data.

Type Hinting

Basically speaking this is a way in which we can force a method or a function to accept a parameter of a specific type. In some cases type hinting is in fact appropriate to use. Let’s take for example, the calling of a catch block that we should specify. Technically, there is no other way to get around this without using type hinting. Because in that way we define the type of the exception. However, the massive usage of type hinting is not a good practice. Since PHP is a dynamic language, it can pretty much enable things to do whatever they want abstractly said, without the need of forcing parameters to be objects. Some of the things that are drawbacks of type hinting in PHP are:

  • It cannot be used in traits
  • Scalar data types are not supported

Let’s write a simple procedural function, same mechanism as in methods. It’ll have the name of go() and will accept one parameter for example $obj. We’ll call it and make a simple var_dump just to check how things are going.

<?php  

go(true);  

function go($obj){  
     var_dump($obj);  
}  

?>  

As expected we get the result.

bool(true)  

If we send a string of true we’ll get:

string(4) "true"  

Let’s set a class which we’ll call TestClass and it won’t have any implementation. It’s gonna be just for a testing purpose so as to proof the concept of our idea about type hinting.

<?php  

go(true);  

function go(TestClass $obj){  
     var_dump($obj);  
}  

class TestClass {  

    function __construct() {  

    }  

}  

?>  

With the above code we tell PHP that the function go() will accept a parameter only if it is from the type TestClass. So what we’re actually doing before the name of the parameter we define the name of the type of object. If we have more than one parameter we just normally separate it by a comma (,).

So if we execute the code like so we’ll get an error stating the following:

Catchable fatal error: Argument 1 passed to go() must be an instance of TestClass, string given, called in ...  

An error that can be escaped with the try, catch mechanism that we’ve talked about earlier in the series. If we send a boolean value, we’ll get the same. So in order for this to work we need to send something that is from the type TestClass.

<?php  

go(new TestClass());  

function go(TestClass $obj){  
     var_dump($obj);  
}  

class TestClass {  

    function __construct() {  

    }  

}  

?>  

Also it should be an object, so we can’t obviously define it as int, string or whatever data type. Type hinting works only with objects and arrays. As well as that we cannot define two types.

Type hinting in PHP requires you to specify types everywhere. Besides it cannot be used in traits and scalar data types are not supported as well (as I said previously in the beginning of the tutorial). If people want to learn technical terminology, they may refer to the documentation then. Apart from that, in high-level languages when we declare a variable we need to define it’s data type, when sending/receiving something as a parameter, it should be defined from what type it should be. So therefore you cannot set boolean, string, integer on a parameter if it doesn’t require it. For example something like that cannot simply be realized in C#:

<?php  

go('true');  

function go($obj){  
  var_dump($obj);  
}  

?>  

The people that use to code in high-level languages influenced PHP to create type hinting. So I don’t think that’s pretty important for object-oriented programming but it is part of it and should be treated as such. Just stating my opinion in these final lines.

Conclusion

Happened to be shorter in comparison to the others. However, it is the sixth part of my series on object-oriented programming in PHP. As I said in the beginning it is a basis that you must handle before we can proceed with the templates in PHP. You can look at it as “the calm before the storm”. Shorter but in the next tutorials it will feel like a piece of cake compared to what I’m planning to present. Thanks for reading!