Share
Web Development

Course Outline

Week 1
Week 2
Week 3
Week 4

OBJECT ORIENTED PROGRAMMING

  • Class
  • Inheritance
  • Class Attributes and Methods
    • Public vas Private
    • Objects
    • Class Variables
    • Constructors
    • Special Methods
Week 5
Week 6

SponsoredAdvertise

Explanations to week content

INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

 

It is important to note that in procedural programming, the functions and the data are separated from one another. In OO programming, data and the functions to manipulate the data are tied together in objects. Objects contain both data (called attributes or properties) and functions to manipulate that data (called methods).

 

An object is defined by the class of which it is an instance. A class defines the attributes that an object has, as well as the methods it may employ. You create an object by instantiating a class. Instantiation creates a new object, initializes all its attributes, and calls its constructor, which is a function that performs any setup operations.

 

A class constructor in PHP5 should be named __construct(), thus two underscores before the construct(), so that the engine knows how to identify it. The following example creates a simple class named User, instantiates it, and calls

its two methods:


General Syntax For A PHP Class

 

<?php
class ClassName{
    //Declare the variables for the class with their appropriate access modifiers (public, protected or private)
    //Declare the constructor to initialize your variables
    public function __construct(declare input variables here){
        //Initialize the class variables with the input variables
        //Use $this->classVariableName = InputVariableName if you decide to make the classVariableName the same as the input     
        //variable name
    }
    //Write the functions (methods) of the class here
}

 

Note


Even though you can write class names as you wish so far as it follows the same format of naming variables, it is advisable to start class names with capital letters.


Example Class


<?php

class Student{
       //Declare the variables for the class e.g
       public $fn;
       public $ln;
       public $student_id;
       //Declare the constructor to initialize your variables
       public function __construct($firstname,$ln,$student_id){
            $fn= $firstname; //No $this-> 
            // because $fn and $firstname variable names are different
           $this->ln = $ln; //$this->ln is needed
           // because the class variable $ln is the same as the input variable name $ln
           $this->student_id = $student_id;
      }
     //class methods come here. Examples
     public function greet(){
         “Welcome to Advance Web Programming, ”.$this->fn.” “.$this->ln;
    }
    public function set_fn($fn){
        $this->fn = $fn;
    }
    public function get_fn(){
        return $fn;
    }
    public function set_ln($ln){
        $this->ln = $ln;
    }
    public function get_ln(){
        return $ln;
    }
    public function set_student_id($student_id){
        $this->student_id = $student_id;
    }
    public function get_student_id(){
         return $this->student_id;
    }
}
?>

     

 

Note


When referring to the variable of the class which has the same variable name as the input variable, the key word $this-> is used. As you have seen above. To refer to the $ln variable in the class, the syntax $this->ln is used,for $student_id, $this->student_id is used but there is no need for $fn because the input variable is of different name ($firstname).

 

Example

 

Write an Employee class. Your class should have the first name, last name, date of birth, id of the employee and the salary of the employee. Use a constructor to initialize the class variables. Your class should have a get_first_name() method to return the first name of the employee, get_last_name() method to return the last name of the employee, get_date_of_birth() method to return the date of birth of the employee, get_id() method to return the id of the employee, get_salary() method to return the salary of the employee and welcome() method to return a welcome message.

 

The Employee Class

 

<?php
class Employee{
     public $fn;
     public $ln;
     public $date_of_birth;
     public $id;
     public function __construct($fn,$ln,$date_of_birth,$id){
            $this->fn= $fn;
            $this->ln= $ln;
            $this->date_of_birth= $date_of_birth;
            $this->id= $id;
       }
       public function get_first_name(){
            return $this->fn;
       }
       public function get_last_name(){
             return $this->ln;
       }
       public function get_date_of_birth(){
             return $this->date_of_birth;
        }
        publicfunction get_id(){
             return $this->id;
        }
        public function welcome(){
             return "Welcome to Advance Web Programming, ".$this->fn." ".$this->ln;
        }
           
}

 

Creating Object Of A Class

 

You need to create object (copy) of the class before you can use the class methods.

 

To create an object of a class, the syntax below is used:

 

$objectName = new ClassName(constructor input values);

 

if the class has no constructor, then the syntax for the object creation will be

 

$objectName = new ClassName();

 

An object for the Employee class could be created as follows:

 

$employee = new Employee(“Benjamin”,”Adjei”,”10-08-2009”,”0012002”);

 

As you can see the constructor input values has been passed during the creation of the object.

 

Benjamin is the first name

Adjei is the last name

10-08-2009 is the date ofbirth

0012002 is the id

 

As you may have noticed, Text values are placed in double quotations.

 

Calling A Method Of A Class

 

Syntax:

 

objectName->methodName(method input values if there is any);

 

For instance to call the welcome method in the Employee class the following syntax could be written.

 

echo “<p>”.employee->welcome().”</p>”;

 

The complete Code for the Employee class could be:

 

<?php
class Employee{
      public $fn;
      public $ln;
      public $date_of_birth;
      public $id;
      public function __construct($fn,$ln,$date_of_birth,$id){
             $this->fn= $fn;
             $this->ln= $ln;
             $this->date_of_birth= $date_of_birth;
             $this->id= $id;
       }
       public function get_first_name(){
            return $this->fn;
       }
       public function get_last_name(){
             return $this->ln;
       }
       public function get_date_of_birth(){
              return $this->date_of_birth;
       }
       public function get_id(){
            return $this->id;
       }
       public function welcome(){
           return "Welcome to Advance Web Programming, ".$this->fn."".$this->ln;
       }
           
}
$employee = new Employee("Benjamin","Adjei","10-08-2006","0012001");
echo"<p>".$employee->welcome()."</p>";
echo "<p>Your first name is:".$employee->get_first_name()."</p>";
echo "<p>Your last name is:".$employee->get_last_name()."</p>";
echo "<p>Your date of birth is: ".$employee->get_date_of_birth()."</p>";
echo "<p>Your employee id is:".$employee->get_id()."</p>";
?>

 

Note

 

If your class is in another php file from where you are creating the object of the class, you will have to include the php file containing the class.

 

The include syntax to use is:

 

include("path_to_your_php_file");

 

e.g

 

include(“classes/employee.php”);

 

In the above example, it means that the employee.php file can be found in the classes folder in the same directory as the file I am creating the object of the class.

 

If the employee.php file is in the same directory as the php file am creating the object, the include syntax will simply be:

 

include(“employee.php”);

 

Inheritance

 

Inheritance is the ability to derive new classes from existing ones and inherit or override their attributes and methods.

 

You use inheritance when you want to create a new class that has properties or behaviors similar to those of an existing class. To provide inheritance, PHP supports the ability for a class to extend an existing class. When you extend a class, the new class inherits all the properties and methods of the parent (with a couple exceptions).You can both add new methods and properties and override the existing ones. An inheritance relationship is defined with the word extends.

 

Let’s create a class Person so we can extend the Person class to create a Student Class.

 

Create a file person.php and write the Person class.

 

person.php

 

<?php
class Person{
     public $fn,$ln,$date_of_birth,$phone,$address;
     public function __construct($fn,$ln,$date_of_birth,$phone,$address){
          $this->fn= $fn;
          $this->ln= $ln;
          $this->date_of_birth= $date_of_birth;
          $this->phone= $phone;
          $this->address= $address;
     }
     /*Methods to get variable values */
     public function get_first_name(){
          return $this->fn;
     }
     public function get_last_name(){
          return $this->ln;
     }
     public function get_date_of_birth(){
          return $this->date_of_birth;
     }
     public function get_phone(){
          return $this->phone;
     }
     public function get_address(){
         return $this->address;
     }
}
?>

 

Create a new class student.php for the Student Class

 

The student class inherits the Person class and we add few additional methods.

 

student.php

 

<?php
include("person.php");
class Student extends Person{
     public $id;
     public $program;
     public function __construct($fn,$ln,$date_of_birth,$phone,$address,$id,$program){
         /*create the parent constructor */
         parent::__construct($fn,$ln,$date_of_birth,$phone,$address);
         /*set the value for the variables which are not in the Person class */
         $this->id= $id;
         $this->program= $program;
     }
     /*Write the new methods in the student class */
     public function get_id(){
          return $this->id;
     }
     public function get_program(){
          return $this->program;
     }
}
/* Create the object of the student class */
$student = new Student("Emelia","Agyei","01-01-2000","0247540305","D14Mango Street, Kejetia","2019001","Computer Science");
/* Greet the student */
echo "<p>Welcome to Advance Web Programming, ".$student->get_first_name()." ".$student->get_last_name()."</p>";
echo "<p>Your date of birth:".$student->get_date_of_birth()."</p>";
echo "<p>Your phone number:".$student->get_phone()."</p>";
echo "<p>Your address:".$student->get_address()."</p>";
echo "<p>Your student id: ".$student->get_id()."</p>";
echo "<p>Your program:".$student->get_program()."</p>";
?>

 

Explanation

 

You must manually call the constructor of the parent class as parent::__constructor() and initialize its variables. parent is as keyword that resolves to a class’s parent class. From the above code, you realize we could call the parent methods get_date_of_birth(), get_phone(),get_address() even though we have not written that method in our student class.

 

Encapsulation

 

Encapsulation is the ability to hide data from users of the class.

 

Version 5 of PHP provides data-hiding capabilities with public, protected, and private data attributes and methods. These are commonly referred to as PPP (for public, protected, private) and carry the standard semantics:

 

Public—A public variable or method can be accessed directly by any user of the class.

 

Protected—A protected variable or method cannot be accessed by users of the class but can be accessed inside a subclass that inherits from the class.

 

Private—A private variable or method can only be accessed internally from the class in which it is defined. This means that a private variable or method cannot be called from a child that extends the class.

 

Note


If another class is used as a data variable in a class, the methods in the object of the class used as a data variable can be accessed by the syntax below:

$this->objectName->methodInObject(input data if there is any);


Handy Classes


To demonstrate the above syntax, I have created two classes which has handy functions which I have written and we would be using most of them in our subsequent lessons.

These classes are Functions which is in the fn.php file and Database which is in dp.php file. The Functions class will contain general methods(functions) and the Database class will contain our database functions. Anytime we want to write a function which is not database related, we will include that function in our Functions class which is in the fn.php file and anytime we want to write a database function, we will include it in the Database class. 

We will have all our class files in a folder call classes in our main folder.

Create a folder in your project folder in the htdocs of xampp and name it classes. You can name your project folder  week4 or however you choose. In the classes folder, create the following files and place their corresponding codes in them.


fn.php


<?php
class Functions{
	function session(){
		return "skullapp";
	}
	function company(){
		return "";
	}
	function noreply(){
		return "noreply@example.com";
	}
	function encrypt_password($password)
	{
		return md5($password);
	}
	function username($fn,$ln)
	{
		return ucwords(strtolower($fn))." ".ucwords(strtolower($ln));
	}
	function clean_name($name){
		return ucwords(strtolower($name));
	}
	function sanitize($text) 
	{
		$text = htmlspecialchars($text, ENT_QUOTES);
		$text = str_replace("\n\r","\n",$text);
		$text = str_replace("\r\n","\n",$text);
		$text = str_replace("\n","<br>",$text);
		return $text;
	}
	function unsanitize($text){
		return str_replace("<br>","\n",$text);
	}
	function send_email($content,$to,$subject)
	{
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= 'To: '.$to."\r\n";
		$headers .= 'From:'.$this->company().'<'.$this->noreply().'>' . "\r\n";
		ini_set("sendmail_from", "");
		if(mail($to, $subject, $content, $headers))
		{
			return true;
		}else{
			return false;
		}
	}
	function generate_token() {
		$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
		$pass = array();
		$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
		for ($i = 0; $i < 20; $i++) {
			$n = rand(0, $alphaLength);
			$pass[] = $alphabet[$n];
		}
		return implode($pass); //turn the array into a string
	}
	function format_amount($amount,$decimal_places)
	{
		return number_format($amount,$decimal_places);
	}
	function option_selected($value,$compareto){
		if($value==$compareto){
			return "selected";
		}else{
			return "";
		}
	}
	function checked($value,$compareto){
		if($value==$compareto){
			return "checked";
		}else{
			return "";
		}
	}
	function validate_int($value){
		if(!ctype_digit($value)){
			return false;
		}else{
			return true;
		}
	}
	function validate_password($password)
	{
		/*/Password length must be greater than or equal to 8 for security reasons*/
		if(strlen(utf8_decode($password))<8)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	function get_client_ip() 
	{
		$ipaddress = '';
		if (getenv('HTTP_CLIENT_IP'))
			$ipaddress = getenv('HTTP_CLIENT_IP');
		else if(getenv('HTTP_X_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
		else if(getenv('HTTP_X_FORWARDED'))
			$ipaddress = getenv('HTTP_X_FORWARDED');
		else if(getenv('HTTP_FORWARDED_FOR'))
			$ipaddress = getenv('HTTP_FORWARDED_FOR');
		else if(getenv('HTTP_FORWARDED'))
		   $ipaddress = getenv('HTTP_FORWARDED');
		else if(getenv('REMOTE_ADDR'))
			$ipaddress = getenv('REMOTE_ADDR');
		else
			$ipaddress = 'UNKNOWN';
		return $ipaddress;
	}
	function validate_email($email)
	{
		$email = strtolower($email);
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
		{
		  return false; 
		}
		else
		{
			return true;
		}
	}
	function get_extension($str) 
	{
		$i = strrpos($str,".");
		if (!$i) { return ""; }
		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);
		return strtolower($ext);
	}
	function validate_image($file){
		$allowed_extensions = array("jpg","jpeg","png","gif");
		$ext = strtolower($this->get_extension($file));
		if(in_array($ext,$allowed_extensions)){
			return true;
		}else{
			return false;
		}
	}
	function validate_date($day,$month,$year){
		if (checkdate($month, $day, $year)){
			return true;
		}else{
			return false;
		}
	}
	function change_date_to_day_month_year($date){
		$atoms = explode("-",$date);
		return $atoms[2]."/".$atoms[1]."/".$atoms[0];
	}
	function change_date_to_year_month_day($date){
		$atoms = explode("/",$date);
		return $atoms[2]."-".$atoms[1]."-".$atoms[0];
	}
	function empty_space(){
		return "&nbsp;";
	}
	function add_emptyspace($total){
		$space = "";
		for($i=0;$i<$total;$i++){
			$space .=$this->empty_space();
		}
		return $space;
	}
	function is_valid_date_range($from_date,$to_date){
		$from_time = strtotime($from_date);
		$to_time = strtotime($to_date);
		if($to_time>=$from_time){
			return true;
		}else{
			return false;
		}
	}
	function generate_digits($digits){
		return str_pad(rand(0,pow(10,$digits)-1),$digits,'0',STR_PAD_LEFT);
	}
}


db.php


<?php
class Database{
	private $fn;
	public function __construct($fn){
		$this->fn = $fn;
	}
	/* Database Connectivity */
	function db_host(){
		return "localhost";
	}
	function db_username(){
		return "root";
	}
	function db_password(){
		return "";
	}
	function db_name(){
		return "test";
	}
	function db_connect(){
		$con = @mysqli_connect($this->db_host(),$this->db_username(),$this->db_password(),$this->db_name());
		return $con;
	}
	function db_close($con){
		mysqli_close ($con);
	}
	/* GENERAL FUNCTIONS */
	function escape($con,$str){
		return mysqli_real_escape_string ($con ,$str);
	}
	function db_rows($con,$sql){
		$result = mysqli_query($con,$sql);
		$num_rows = mysqli_num_rows($result);
		return $num_rows;
	}
	function authenticate($username,$password){
		$con = $this->db_connect();
		$sql = "select * from users where lower(username)=lower('".$this->escape($con,$username)."') and password='".$this->fn->encrypt_password($password)."' and block=0";
		if($this->db_rows($con,$sql)>0){
			$query = mysqli_query($con,$sql);
			while($row=mysqli_fetch_array($query)){
				$id = $row['id'];
			}
			$_SESSION[$this->fn->session()] = $id;
			/* Update last login ip address and time */
			$sql = "update users set last_login_ipaddress='".$this->fn->get_client_ip()."', last_login=NOW() where id=".intval($id);
			mysqli_query($con,$sql);
			$this->db_close($con);
			return true;
		}else{
			$this->db_close($con);
			return false;
		}
	}
}


Note


The Database class uses some of the functions in the Function class hence the Function class is used as a data variable which is initialized in the Database constructor.

private $fn;
public function __construct($fn){
  $this->fn = $fn;
}

As you can see in the Database class, the Function class object would be passed in the Database class constructor anytime the database object is created. This Function object is used to initialize the $fn data variable. This makes the $fn variable also a Function class object and therefore has all the methods of the Function class.

You can see the use of some of the syntax written above for invoking methods in the Function class.


Syntax


$this->objectName->methodInObject(input data if there is any);


Example usage in the Database Class


$_SESSION[$this->fn->session()] = $id;


Explanation


The object name for the Function class in the database class is $fn. Hence to access the session() method from the Function object, the above syntax is used.


$this->fn->session()


Which is the $this->objectName(fn)->methodName(session());

Another example can be seen in the below code in the Database class

$sql = "update users set last_login_ipaddress='".$this->fn->get_client_ip()."', last_login=NOW() where id=".intval($id);


The get_client_ip() is a method in the Function class. Hence to access that method in the database class, the above syntax is used.


$this->fn->get_client_ip()



In order for us not to be writing the same script over and over for including our classes in our project files, we will include all the classes in a file we will name init.php so we simply have to include only this file in all our project files that will need any of our classes. The init.php file should be in your main folder where you have your php files for the project.

init.php


<?php
include("classes/fn.php");
include("classes/db.php");
?>


As you can see, the init file includes the fn.php and db.php files which are located in the classes folder. These files contain the Functions and Database classes respectively.

We will see more of the database functions in the subsequent week when we start the database topic. 

I will demonstrate how the class objects can be created and few of the Function class methods called in the php script below.  

Create your init.php file in the main project and include its code.

In the same main project folder, create a file call demo.php and include the code below:

demo.php


<?php
include("init.php");
$fn = new Functions();
$db = new Database($fn);
?>
<p><b>Encrypt password (kuulchat)</b></p>
<p><?php echo $fn->encrypt_password("kuulchat");?></p>
<?php
$day = 31;
$month = 2;
$year = 2020;
?>
<p><b>Validate Date(<?php echo $day."/".$month."/".$year;?>)</b></p>
<?php
if($fn->validate_date($day,$month,$year)){
?>
<p>Date is ok</p>
<?php
}else{
?>
<p>Date is invalid</p>
<?php
}
?>


Run your demo.php file.


Explanation to the demo.php script


The init.php file is included which has already included the fn.php and db.php files for our Functions and Database classes respectively.

include("init.php");

An object ($fn) is created for the Functions class.

$fn = new Functions();

The Database class takes a Function object in the constructor hence the function object $fn is passed in the constructor when creating the Database object ($db).

$db = new Database($fn);

Since we haven't considered database yet, I skipped the Database class methods. We will call some of the database methods next week and write few new methods to our current methods in the Database class.

The encrypt_password and validate_date methods where called on the $fn object to encrypt a password (kuulchat) and validate date (31/2/2020) respectively.

$fn->encrypt_password("kuulchat");

Code: For encrypting password

$fn->validate_date($day,$month,$year)

Code: For validating date


Special Methods

 

Classes in PHP reserve certain method names as special callbacks to handle certain events. You have already seen __construct(), which is automatically called when an object is instantiated. The other is __destruct(). It is the callback for object destruction. Destructors are useful for closing resources(such as file handles or database connections) that a class creates. In PHP, variables are reference counted. When a variable’s reference count drops to 0, the variable is removed from the system by the garbage collector. If this variable is an object, its __destruct() method is called.

SponsoredAdvertise

Kuulchat Premium