Introduction to PHP - Object Oriented Programming Part 2

Guest Posts Paolo Nikko Nuñal

In our previous tutorial we discuss about how to create classes this time around we are going to continue with class properties. Add a name, age and gender to the properties that you have created.

<?php
   class Person
   {
       private $name = "John Doe";
       private $age = 23;
       private $gender = "Male";
   }
   $p1 = new Person;
?>


From the code above, we have set the properties of the Person class. To read a property and output it to the browser you need to reference it by using the "->".

 echo $p1->$name


In which it will output the word John Doe.

Creating Class Methods

Classes contains methods, and are class-specific functions. Individual actions that an object does are created through methods. Like how a person eats, sleeps or drinks.  To create methods we normally use getters and setters the same as java. In our previous example, we have already set a value to the properties, however if you want your class to be more dynamic  we need to create methods that will set and get the $name, $age, and $gender of a person.

<?php
   class Person
   {
       private $name 
       private $age
       private $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;
   $p1->setName("Jason");
   echo $p1->getName();
?>


From the code above we have get a getters and setters for each property. To use methods, all you need is just to call them same like any other functions, but always remember to reference the object that they belong to. From the code above, we first created a new Person which is p1. After which, we assigned a name called Jason. What it does it calls the setName() method that accepts one parameter in which we passed the string "Jason". The getName() method returns what we have set which is "Jason". It is a must that you always reference the object that you are referring to. As you can instantiate as many Person as you wish.