LearnMagic methods and constants unveiled

Magic methods and constants unveiled

Object Oriented PHP offers several magic methods and constants that enable a lot of programming with very little code, but which suffer from a few disadvantages like a slight reduction in the performance time as well as in the level of code clarity.

There is much dispute about the use of magic methods, so in this tutorial we explain the parts of the field which are widely agreed, but ignore the parts in dispute.

The __construct() magic method

The names of magic methods always start with two underscores, and the __construct() magic method is no exception. We use __construct() in order to do something as soon as we create an object out of a class. A method of this kind is called a constructor. Usually we use the constructor to set a value to a property.

In our simple example, we want to set the value of the $model property as soon as we create the object, so we add a constructor inside the class that sets the value of the $model property.

class Car{
  private $model;
 
  // A constructor method.
  public function __construct($model)
  {
    $this -> model = $model;
  }
}

In order to use the constructor, we have to pass an argument to the class with the name of the model as soon as we create the object, but if we try to create a new object without assigning the value that the constructor needs, we will encounter an error.

$car1 = new Car();

Result:
Warning: Missing argument 1 for Car::__construct()

In order to avoid such an error, we have to assign a value to the constructor. Thus, for the sake of example, we assign the value "Mercedes" to the constructor by writing it within the brackets of the newly created object.

$car1 = new Car("Mercedes");

Now, let’s add the method getCarModel() in order to echo the car model from the object that we have just created.

class Car {
  private $model;
  
  //__construct
  public function __construct ($model)
  {
    $this -> model = $model;
  }
   
  public function getCarModel()
  {
    return ' The car model is: ' . $this -> model;
  }
}
  
//We pass the value of the variable once we create the object
$car1 = new Car("Mercedes");
  
echo $car1 -> getCarModel();

Result:
The car model is: Mercedes.

How to write a constructor method without risking an error?

When we try to create an object that has a constructor method, we run the risk of our code breaking if we don’t pass a value to the constructor. In order to avoid this risk, we can define a default value for the properties that we would like to set through the constructor. The default value may be the most reasonable choice for the property, zero, an empty string, or even a null.

If we use a null as the default value, we can use a condition to assess if a value was passed and then, only in that case, assign the value to the property.

In the example below, we give a default value of null to the $model property and, only if a value is passed to the constructor, we assign this value to the property. In any other case, the $model property has a default value of "N/A" string.

class Car {
  // The $model property has a default value of "N/A"
  private $model = "N/A";
  
  // We don’t have to assign a value to the $model property
  //since it already has a default value
  public function __construct($model = null)
  {
    // Only if the model value is passed it will be assigned
    if($model) 
    { 
      $this -> model = $model;
    }
  }
   
  public function getCarModel()
  {
    return ' The car model is: ' . $this -> model;
  }
}
  
//We create the new Car object without passing a value to the model
$car1 = new Car();
  
echo $car1 -> getCarModel();

Even though we created the object without passing a value to the model property, we didn't cause an error because the model property in the constructor has a default value of null.

Result:
The car model is: N/A

On the other hand, let’s see what happens when we define the model once we create the object. In the example, we assign the value "Merceds" to the $model property as soon as we create the object.

class Car {
  private $model = '';
 
  //__construct
  public function __construct($model = null)
  {
    if($model) 
    { 
      $this -> model = $model;
    }
  }
  
  public function getCarModel()
  {
    return ' The car model is: ' . $this -> model;
  }
}
 
//We create the new Car object with the value of the model
$car1 = new Car('Mercedes');
 
echo $car1 -> getCarModel();

Result:
The car model is: Mercedes

Magic constants

In addition to magic methods, the PHP language offers several magic constants.

For example, we may use the magic constant __CLASS__ (magic constants are written in uppercase letters and prefixed and suffixed with two underlines) in order to get the name of the class in which it resides.

Let’s take a look at the following example in which we use the __CLASS__ magic constant in the getCarModel() method to get the class's name:

class Car {
  private $model = '';
  
  //__construct
  public function __construct($model = null)
  {
    if($model) 
    { 
      $this -> model = $model;
    }
  }
   
  public function getCarModel()
  {
    //We use the __CLASS__ magic constant in order to get the class name
  
    return " The <b>" . __CLASS__ . "</b> model is: " . $this -> model;
  }
}
  
$car1 = new Car('Mercedes');
  
echo $car1 -> getCarModel();

Result:
The Car model is: Mercedes

Other magic constants that may be of help are:

__LINE__ to get the line number in which the constant is used.
__FILE__ to get the full path or the filename in which the constant is used.
__METHOD__ to get the name of the method in which the constant is used.

Conclusion

In this tutorial, we have learned about magic methods and constants, and how to use constructors to set the values of properties as soon as we create objects out of classes. Click here to practice the subject.

In the next tutorial, we will learn about inheritance, a principle of the object oriented programming that can save us from repeating ourselves.

comments powered by Disqus