Introduction to PHP - Object Oriented Programming Part 3

Guest Posts Paolo Nikko Nuñal

In the last tutorial we discussed on how to create methods and how effective OOP can be when dealing with programming tutorials. In this tutorial, we are going to discuss Magic Methods in OOP.

To even make OOP in PHP much easier than ever, PHP provides magic methods. The first one we are going to tackle about is Constructors and Destructors. If you are familiar with Java, creating a constructor is easy and all you need to do is to name it the same as the class. However, in PHP you can do so by using the magic method __construct() to do so.

So what is a constructor? Consider a constructor as a function that is executed after the object has been initialized. Consider it as a mold, in which it "constructs" the class without having you to call each "set" methods one by one to create.

<?php
   class Person
   {
       private $name 
       private $age
       private $gender
   }
   public __construct($name,$age,$gender)
   {
       $this->name = $name;
       $this->age  = $age;
       $this->gender = $gender;
   }
   public function setName($name)
   {
      $this->name = $name
   }
   public function getName()
   {
      return $this->name;
   }
   public function setAge($age)
   {
      $this->age = $age;
   }
   public function getAge()
   {
      return $this->age;
   }
   public function setGender($gender)
   {
      $this->gender = $gender;
   }
   public function getGender()
   {
      return $this->gender;
   }

   $p1 = new Person("John Doe",24,"MALE");
   echo $p1->getName();
   echo $p1->getAge();
   echo $p1->getGender();
?>


From the code above, we created a constructor using the magic method _construct(), in which it accepts three parameters. When we instantiate a new object which is $p1, we passed three variables that contains string and numbers that is Person("John Doe",24,"MALE"). That statement automatically invokes the _construct() method, and "creates" a new Person using the parameters being passed on the constructor.

Instead of calling individually the setName, setGender, setAge methods, we can easily create one by calling the __constructor().