Object Oriented Programming In PHP Part Three – Constructor & Destructor

PHP offers many “special” methods called magic methods. Today I will write about two of them. This is the third part of the Object Oriented Programming in PHP series and, if you haven’t already, I suggest you first read part one and two. The methods we will take a look at today are called constructor and destructor.

All magic methods names start with two underscores. To implement constructor and destructor we have to override __construct() and __destruct() methods. The method __construct is invoked when we create an object and __destruct when all references on an object are removed or an object is explicitly destroyed.

class MilitaryBaracks {
 
  // note that construct methods starts with two underscores
  public function __construct() {
    // this code executes when object is created
    echo "Soldier " . $this->name . " was created.";
  }

  // ... rest of the class code
  
  public function __destruct() {
    // this code executes when object is destroyed
    echo "Destroying solider with name " . $this->name;
  }
}

We use constructor in cases, when we want to execute some piece of code when object is instantiated. For instance, set values to properties for which we want to be sure they are set. In case of a class which takes care of connecting to database, we would want to be sure that we have all data required for establishing connection. We could use destructor to close the connection. In practice, constructor is much more often used than destructor because PHP closes resources it uses when script finishes execution. Anyway, this stackoverflow link offers few examples of uses of destruct method in open source code.

For the sake of clarity, let’s build upon our MilitaryBaracks example. We want to be sure that every soldier has name and weapon.

class MilitaryBaracks {
 
  // name doesn't have default value no more
  private $_name;
  // so doesn't weapon
  private $_weapon;
 
  private $_ammunition = 10;
 
  // instead, we make sure that values are passed when object is created
  public function __construct($name, $weapon) {
    $this->_name = $name;
    $this->_weapon = $orozje;
  }

  // we want that soldier is able to switch weapon
  // so we create getter method to access weapon variable value
  public function getWeapon() {
    return $this->_weapon;
  }
 
  // and set method to switch weapon
  public function setWeapon($weapon) {
    $this->_weapon = $weapon;
    return $this;
  }
 
  // name can't be changed, so we create only getter method
  public function getName() {
    return $this->_name;
  }
 
  //...
}

Ookay, let’s print out a few lines:

// this is wrong because of missing arguments
$soldier = new MilitaryBaracks();
// the right way
$soldier = new MilitaryBaracks('Mougli', 'rifle');
 
echo $soldier->getname() . " has weapon " . $soldier->getWeapon() . ".<br>";
 
$soldier->setWeapon('gun');

echo $soldier->getName() . " has weapon " . $soldier->getWeapon() . "."; 

And we get:

Warning: Missing argument 1 for MilitaryBaracks::__construct(), called in C:\Programi\Wamp\www\script.php on line 41 and defined in C:\Programi\Wamp\www\script.php on line 13

Warning: Missing argument 2 for MilitaryBaracks::__construct(), called in C:\Programi\Wamp\www\script.php on line 41 and defined in C:\Programi\Wamp\www\script.php on line 13

Notice: Undefined variable: name in C:\Programi\Wamp\www\script.php on line 14

Notice: Undefined variable: weapon in C:\Programi\Wamp\www\script.php on line 15

Mougli has weapon rifle.
Mougli has weapon gun.

This way our object are easier to instantiate and set, since we do everything in one line. Beside that, now we can be pretty sure that our objects have all needed properties set, as PHP throws a warning if we leave out an argument when instantiating new object. Our code and classes needs to be organized in a way that other programmers can easily understand its meaning and structure. The predictability is important “guide” of OOP.

Even though I previously announced a blog post about inheritance I saved it for next time. I intended to present constructor and inheritance in this post, but it would be too long and I want to keep series short and simple. For that reason I cover it in the next post.

Leave a Reply