Jump to: navigation, search

PHP Object Oriented

From w3cyberlearnings

Contents

PHP Object Oriented

  • If you just start to program, you will not familiar with the concept of object-oriented Programming Language.
  • PHP is also supported object oriented programming language.
  • When you develop the application based on the object-oriented programming language concept, you program is easy to expend and modify.
  • In addition, by develop your program in the object oriented method, it makes your design and development easier.

What is that mean?

  • Let consider a car, a car makes from many parts or components.
  • A car has four wheels, a machine, four doors, and many other components.
  • Some car has its own unique design, but it shares many major unique components.
  • For that situation, if we develop a car object, we have to make sure all the common features are within the car object.
  • Finally, we can extend the car object for other type of car for example for a Toyota car.
  • In this way, we called the new object Toyota object which in turn inherited from the car object.
  • When the Toyota object inherited from the car object, the Toyota object is also inherited all the properties of the car object.

Object Oriented Syntax

  class car {

  }

  class Toyota extends car {

  }

Code (SimpleClass.php)

  • We create a PHP class and named it SimpleClass.
  • This class has one public function called sayHello().
  • A class keyword uses to declare a class, and it follows by a class name.
  • For convenience, we named the file the same as the class name.
<?php
class SimpleClass {
    public function sayHello() {
        echo "hello world" . "<br/>";
    }
}
?>

Code (testSample.php)

  • We need to import the SampleClass.php file in order for us to use the SampleClass class.
  • The following is how to create the SampleClass object.
  • Example: $sample1 = new SampleClass();
<?php
    require_once 'SampleClass.php';        // we import the SampleClass.php

    $sample1 = new SampleClass();
    $sample1->sayHello();
?>

Result

hello world

PHP Constructor

  • In PHP5, constructor methods can be created for a class.
  • We can initialize class's property before it can be used within the constructor method.
  • If the class is inherited from another class, and we need to call the parent constructor.
  • Call the parent constructor class: this parent::__construct()

Code (testClass.php)

  • We create a class called a Constructor class, and in this class contains a variable named $message.
  • We initialized the default value for the $message variable in the class's constructor.
  • Finally, when we create a Constructur object, and from the class object, we called the display_message() method.
  • The display_message() method displays the $message default value that initialized within the class constructor.
<?php

class Constructor {
    private $message ;

    public function  __construct() {
        $this->message = "Hello this assign in the constructor method <br/>";
    }
    public function display_message() {
        echo "<br/>". $this->message . "<br/>";
    }
}

$test_class = new Constructor();
$test_class->display_message();

?>

Display Result

Hello this assign in the constructor method
Parent's constructor class

Parent and Child Class Example (person.php)

  • In this sample codes we demonstrate the child and parents relationship.
<?php

// parent class
class person {
    protected $name;
    protected $age;
    public function  __construct($name, $age) {
        $this->age = $age;
        $this->name = $name;
    }
    public function display_person() {
        echo "Name: " . $this->name . "<br/>";
        echo "Age:"   . $this->age  . "<br/>";
    }
}

// child class
class employee extends person {
    protected $department;
    protected $employee_id;

    public function  __construct($name, $age,$department, $employee_id) {
        parent::__construct($name, $age);
        $this->department = $department;
        $this->employee_id = $employee_id;
    }

    public function display_employee() {
        parent::display_person();
        echo "Department: " . $this->department . "<br/>";
        echo "Employee Id: ". $this->employee_id . "<br/>";
    }
}

// demonstrate
$emp = new employee("John",20,"IT","32455333");
$emp->display_employee();
?>

Display Result

Name: John
Age: 20
Department: IT
Employee Id: 32455333

PHP Class Destructor

  • Destructor class is called when the object is explicitly destroyed or no long used.
  • In the destructor method, we can close connection or release memory back to the system.

A constructor method and the destructor method(testClass.php)

  • We create a constructor and destructor methods.
  • When we instantiated the Constructor class, and we assigned the default value for the $message variable.
  • When the Constructor class is not longer used, the destructor method is called.
<?php

class Constructor {
    private $message ;

    public function  __construct() {
        $this->message = "Hello this assign in the constructor method <br/>";
    }
    public function __destruct() {
        echo "<br/>destroy it here!"<br/>";
    }
    public function display_message() {
        echo "<br/>". $this->message . "<br/>";
    }
}

$test_class = new Constructor();
$test_class->display_message();
?>

Display Result

Hello this assign in the constructor method
Destroy it here

PHP Class/Assoc array

  • In this tutorial, a class's constructor method which accepts an associative array as an argument.
  • It assigns the associative array to the class's property.

Code (studentClass.php)

<?php
class studentClass {
    protected $name;
    protected $major;
    protected $year;
    // this constructor method accept a single argument,
    // this single argument is an associate array
    public function  __construct($student_arr) {
        $this->name = $student_arr["name"];
        $this->major = $student_arr["major"];
        $this->year = $student_arr["year"];
    }

    // we display a student information
    public function display_student() {
        echo "Name:  ". $this->name . "<br/>";
        echo "Major: ". $this->major. "<br/>";
        echo "Year:".   $this->year . "<br/>";
    }
}
// we create an associate array for student
$bob_arr = array('name'=>'Bob Zoe','major'=>'computer science','year'=>2008);

// we assign the array $bob_arr to the class
$student_bob = new studentClass($bob_arr);
$student_bob->display_student();
?>

Display Result

Name: Bob Zoe
Major: computer science
Year:2008

PHP Final Keyword

  • We can use the final keyword in front of a class or a function.
  • A class or function declared as final, this class or function can not be extended or inherited.

Code (finalClass.php)

  • This class can not be extended by any other classes.
  • It's also mean no class can be inherited from this class.
<?php

final class finalClass {
    public function displayHello() {
        echo "Hello";
    }
}

$finalClass = new finalClass();
$finalClass->displayHello();
?>

Final Functions (finalFunction.php)

  • When a function declared as final, this function can not be redeclared by child class.
  • It's also mean no child class can re-declare or override this function.
<?php

class ourClass {
    public function displayHello() {
        echo "Hello";
    }
    final public function displayMessage() {
        echo "Hello message!! <br/>";
    }
}

class childClass extends ourClass {
    public function displayMessage() {
        echo "bad style";
    }
}
$testClass = new childClass;
$testClass->displayMessage();
?>

Display Result

We have tried to override the function in the child class, as the result it generates the error messages.

Fatal error: Cannot override final method ourClass::displayMessage() in 
/var/www/xprofile/class/finalClass.php on line 26

PHP Private Keyword

  • A private variable or function prevents user from accessing them directly.
  • If we try to access the private variable or function, we will get an error message!!

Code (personPrivate.php)

  • Accessing private variables or functions is not allow.
<?php
class personPrivate {
    private $ssn;
    private $date_of_birth;
    private $driver_license;

    public function  __construct() {
        $this->ssn = 'N/A';
        $this->date_of_birth='N/A';
        $this->driver_license = 'N/A';
        echo "constructor class <br/>";
    }
    private function birthDate() {
        return $this->date_of_birth;
    }
    public function setPerson($ssn, $dob, $driver) {
        $this->date_of_birth = $dob;
        $this->ssn = $ssn;
        $this->driver_license = $driver;
    }
    public function display() {
        echo "<br/> SSN:", $this->ssn , "<br/>";
        echo "<br/> Date of birth:", $this->birthDate(), "<br/>";
        echo "<br/> Driver License:", $this->driver_license, "<br/>";
    }
}

$personTest = new personPrivate();
$personTest->setPerson("333-22-4444", "4/5/2000", "424-4223123");
$personTest->display();

// we cant access the attributes directly
// we will get an error message
// Fatal error: Call to private method personPrivate::birthDate() from context

$personTest->ssn='222-344-4444';
$personTest->birthDate();
?>

Display Result

  • As you can see, accessing the class private method or variable will generate an error message.
constructor class
SSN:333-22-4444
Date of birth:4/5/2000
Driver License:424-4223123
Fatal error: Call to private method personPrivate::birthDate() from context

PHP Public Keyword

  • A public function or variable means that everyone can access it.
  • When we declare a variable or function as public, we allow the public to access it directly.

Code(Department.php)

  • We can access the $message variable directly.
  • If we have declared the message variable as private or protected, we will get an error message when we try to access them.
<?php
class Department {
    public $message;
    public function Display() {
        echo "This is " , $this->message , "<br/>";
    }
}

$dept = new Department();
$dept->message = "<b>hello world</b>";
$dept->Display();

echo "here how we call the public attribute ", $dept->message , "<br/>";
?>

Display Result

This is hello world
here how we call the public attribute hello world

PHP Protected Keyword

  • Protected keyword is similar to the private keyword.
  • When a parent class declare a variable or function as protected, we can access that variable or function in the child class as thought it is declared as public.
  • When we instantiated a class that have the variable or function declared as protect, we will not allow to directly access that variable or function.

Code (protectedClass.php)

<?php
class ParentClass {
    protected $name;
    protected $age;
}

class ChildClass extends ParentClass {
    public $dept;
    public function  __construct() {
        $this->dept = "n/a";
        $this->age = "n/a";
        $this->name = "n/a";
    }

    public function setProperty($dept, $name, $age) {
        $this->dept = $dept;
        $this->age = $age;
        $this->name = $name;
    }

    public function getAge() {
        return $this->age;
    }
    public function getName() {
        return $this->name;
    }
    public function getDept() {
        return $this->dept;
    }
}

$child_test = new ChildClass();
$child_test->setProperty("IT", "Souphal", 21);

echo "<br/> Age : ", $child_test->getAge() , "<br/>";
echo "<br/> Name: ", $child_test->getName() , "<br/>";
echo "<br/> Dept: ", $child_test->getDept() , "<br/>";

?>

Display Result

Age : 21
Name: Souphal
Dept: IT

PHP Object Oriented Car

  • From the previous tutorial, we have discussed some of the foundation of object-oriented and how to design the object in PHP.
  • In this tutorial, we are going to design a car object.
  • A car object contains: name, engine, doors, wheel, color, year, and many other components.
  • Different car model has different features. However, all cars share common attributes and functions.

Car.php (A basic car object)

  • In this car class, we have declared six protected variables.
  • A protected variable or function is accessible by a child class.
  • Protected variable or function prohibit the instance object to directly access the class variable or function.
  • Only the child class can access the protected variable or function.
  • Because the variables are not publicly accessible, we need to create setter methods (public function setName($name)) to set the variable value, and the the getter methods (public function getName()) to get the variable value.
<?php

class Car {
    // declared 6 privated variables
    protected $name,$engine, $door, $wheel, $color, $year;
    // default constructor, and we have initialized default value
    public function  __construct() {
        $this->door   = 4;
        $this->engine = '4 cylinder';
        $this->wheel  = '4x4';
        $this->year   = 2011;
        $this->color  = 'silver';
        $this->name   = 'None';
    }
    public function setProperties($data) {
        $this->name   = $data["name"];
        $this->engine = $data["engine"];
        $this->door   = $data["door"];
        $this->wheel  = $data["wheel"];
        $this->color  = $data["color"];
        $this->year   = $data["year"];

    }
    public function setName($name) {
        $this->name = $name;
    }
    public function getName() {
        return $this->name;
    }

    public function setEngine($engine) {
        $this->engine = $engine;
    }
    public function getEngine() {
        return $this->engine;
    }

    public function setDoor($door) {
        $this->door = $door;
    }
    public function getDoor() {
        return $this->door;
    }

    public function setWheel($wheel) {
        $this->wheel = $wheel;
    }
    public function getWheel() {
        return $this->wheel;
    }

    public function setColor($color) {
        $this->color = $color;
    }
    public function getColor() {
        return $this->color;
    }

    public function setYear($year) {
        $this->year = $year;
    }
    public function getYear() {
        return $this->year;
    }
    public function display() {
        echo "<hr>";
        echo 'Name   :'.   $this->getName().    "<br/>";
        echo 'Year   :'.   $this->getYear() .   "<br/>";
        echo 'Engine :'.   $this->getEngine() . "<br/>";
        echo 'Color  :'.   $this->getColor().    "<br/>";
        echo 'Wheels  :'.   $this->getWheel().   "<br/>";
        echo 'Doors   :'.   $this->getDoor().    "<br/>";
    }
}
?>

Code (TestCar.php) (Test the car class)

  • We imported the Car.php file, and we create the car object.
<?php

require_once 'Car.php';
/*
 *  create a car object
 *  and we call the display() function,
 *  we get the default value, because we haven't set any attribute yet
 *
 */

$new_toyota = new Car();
echo "<br/><b>Display default attribute values</b><br/>";
$new_toyota->display();

/*
 * We create $data_car array
 * We call the setProperties($data_car) to assign the car's attributes
 * Finally, we call the display() function
 *
 */

$data_car = array(
        'name'=>'Toyota',
        'engine'=>'4 cylinder',
        'door'=>'4',
        'wheel'=>'2 wheel drive',
        'color'=>'black',
        'year'=>2011
);

echo "<br/><b>Set the attribute value from the array</b><br/>";
$new_toyota->setProperties($data_car);
$new_toyota->display();

/*
 * we call the setter functions to set the attributes
 * Finally, we call the display() function
 */

$new_toyota->setYear(2012);
$new_toyota->setColor("blue");
$new_toyota->setDoor("4");
$new_toyota->setEngine("4 cylinder");
$new_toyota->setWheel("2 wheel drive");
$new_toyota->setName("Honda");
$new_toyota->display();

/*
 * We create a list of array
 * and we loop through the array with foreach
 * Finally, we call the display() function to display the car
 */

$data_all = array(
        'Toyota Camery'=> 
            array(
                 'name'=>'Toyota Camery',
                 'engine'=>'4 cylinder',
                 'door'=>4, 
                 'wheel'=>'2 wheel drive', 
                 'color'=>'silver',
                 'year'=>2012),

        'Honda Accord' => 
            array(
                 'name'=>'Honda Accord',
                 'engine'=>'6 cylinder', 
                 'door'=>2, 
                 'wheel'=>'2 wheel drive',
                 'color'=>'blank',
                 'year'=>2012),

        'BMW'=> array(
                 'name'=>'BMW 530i',
                 'engine'=>'6 cylinder',
                 'door'=>4, 
                 'wheel'=>'2 wheel drive',
                 'color'=>'blank',
                 'year'=>2012)
    );

echo "<br/><b>Set the attribute value from the array list</b><br/>";
foreach ($data_all as $k=>$v) {
    $new_toyota->setProperties($v);
    $new_toyota->display();
}
?>

Display Result

Name :None
Year :2011
Engine :4 cylinder
Color :silver
Wheels :4x4
Doors :4

Set the attribute value from the array

Name :Toyota
Year :2011
Engine :4 cylinder
Color :black
Wheels :2 wheel drive
Doors :4

Name :Honda
Year :2012
Engine :4 cylinder
Color :blue
Wheels :2 wheel drive
Doors :4

Set the attribute value from the array list

Name :Toyota Camery
Year :2012
Engine :4 cylinder
Color :silver
Wheels :2 wheel drive
Doors :4

Name :Honda Accord
Year :2012
Engine :6 cylinder
Color :blank
Wheels :2 wheel drive
Doors :2

Name :BMW 530i
Year :2012
Engine :6 cylinder
Color :blank
Wheels :2 wheel drive
Doors :4

PHP Inherit Car Class

  • In this tutorial, we create the BMW class and this class inherits from the Car class.
  • We have included the controller and bmw_serial variables for the BMW class.
  • We also created the setter and getter functions.
  • We use the extends keyword to inherit from a parent class.

Inherit from Car class (BMW.php)

  • The BMW class included the Car.php file in order to use the Car class.
  • We created two variables, and we have initialized the default value for these variables in the constructor class.
  • In addition, we called the parent's constructor class parent::__construct() within the child class (BMW) constructor.
  • We declared two private variables, and we need the setter and getter functions in order to set private variable value.
  • To call the function in the parent's class, we need to use parent::functionName().

parent::display();

<?php

require_once 'Car.php';

class BMW extends Car{
    
    private $controller;
    private $bmw_serial;

    public function  __construct() {
        parent::__construct();
        $this->bmw_serial = 'n/a';
        $this->controller = 'n/a';
    }

    public function setController($controller) {
        $this->controller = $controller;
    }
    public function getController() {
        return $this->controller;
    }

    public function setSerial($serial) {
        $this->bmw_serial = $serial;
    }
    public function getSerial() {
        return $this->bmw_serial;
    }
    public function  display() {
        parent::display();
        echo "Controller: " . $this->controller . "<br/>";
        echo "Serial Number:" . $this->bmw_serial . "<br/>";
    }
}

$new_bmw = new BMW();
$new_bmw->display();

$new_bmw->setName("BMW 740i");
$new_bmw->setEngine("6 cylinder");
$new_bmw->setDoor(4);
$new_bmw->setYear(2012);
$new_bmw->setColor("black");
$new_bmw->setWheel("2 wheel drive");
$new_bmw->setSerial("bwm32342432240");
$new_bmw->setController("Advanced Control System");
$new_bmw->display();
?>

Display Result

Name :None
Year :2011
Engine :4 cylinder
Color :silver
Wheels :4x4
Doors :4
Controller: n/a
Serial Number:n/a

Name :BMW 740i
Year :2012
Engine :6 cylinder
Color :black
Wheels :2 wheel drive
Doors :4
Controller: Advanced Control System
Serial Number:bwm32342432240

PHP Abstract Class

  • Any class that defined as abstract can no be instantiated, and we inherit the abstract class with the extends keyword.
  • All the methods in the abstract class that declared as abstract must be defined in the child class.
  • If the method in the abstract class defined as protected, we need to either define it as protected or public, not private.
  • An abstract class does not need to be a based class, and the abstract class could be inherited from another class.
  • We define the abstract class as the class skeleton.
  • The abstract class contains variables and member methods.
  • Member methods of the abstract class can be completed or incompleted.
  • The derived class that extends the abstract class provides a full functionality for the incomplete member methods.
  • When do we need an abstract class? A class that is generic to all other class, should be created as abstract.
  • Thus all other classes can inherit from it. Within the abstract class, the common method is the method that does not define abstract.
  • We use the abstract class to group the related class together, and abstract class is never declare as final because it is always extendable.

person.php for the abstract class

  • We defined the person class as the abstract class.
  • This person abstract class will be used by other classes.
  • Employee, Employer, Customer can extend this abstract class.
  • The abstract class shares many methods and attributes for other classes.
  • When a child class extends this abstract class, that child class must define the display() and setPerson($firstname, $lastname, $age) functions. If the child class does not define those functions, PHP will generate an error message.

Code (person.php)

<?php

abstract class person {
	protected $first_name;
	protected $last_name;
	protected $age;

	abstract public function display();
	abstract public function setPerson($firstname,$lastname,$age);
}
?>

Code (employee.php) (This class extends/inherit from the person class)

  • The employee class extends the person class, and it defines two public member functions.
  • Without these two member functions, PHP will generate an error message.
  • public function setPerson($fname, $lastname, $age)
  • public function display()
<?php
require_once 'person.php';

class employee extends person {
	public $department;
	public $role;

	public function setPerson($fname, $lastname, $age) {
		$this->first_name = $fname;
		$this->last_name = $lastname;
		$this->age = $age;
	}
	public function display() {
		echo "Department: ". $this->department . "\n";
		echo "Role: ". $this->role. "\n";
		echo "First Name: ". $this->first_name . "\n";
		echo "Last Name: " . $this->last_name . "\n";
		echo "Age: " . $this->age . "\n";
	}

	public function __construct($fname, $lastname, $age) {
		$this->setPerson($fname, $lastname, $age);
	}
}

$employee_1 = new employee('Chrstina','Zhota',21);
$employee_1->department = "HR";
$employee_1->role = "PHP Recruiter";

$employee_1->display();
?>

Display Result

Department: HR
Role: PHP Recruiter
First Name: Chritina
Last Name: Zhota
Age: 21

Code (customer.php) (this class extends the person class)

  • The customer class is another example that it extends the person class.
  • This class defines two member functions.
  • public function display()
  • public function setPerson($fname, $lastname, $age)
<?php
require_once 'person.php';

class customer extends person {
	public $customer_id;
	public $order_date;
	public $cost;
	public $shipping_date;

	public function display() {
		echo "Customer ID: " . $this->customer_id . "\n";
		echo "Order Date: " . $this->order_date .  "\n";
		echo "Cost: " . $this->cost . "\n";
		echo "Shipping Date: " . $this->shipping_date . "\n";
		echo "First Name: ". $this->first_name . "\n";
		echo "Last Name: " . $this->last_name . "\n";
		echo "Age: " . $this->age . "\n";
	}
	public function setPerson($fname, $lastname, $age) {
		$this->first_name = $fname;
		$this->last_name = $lastname;
		$this->age = $age;
	}
}

$customer1 = new customer();
$customer1->customer_id = "20311";
$customer1->order_date = "04/14/2011";
$customer1->cost = "20";
$customer1->shipping_date = "04/15/2011";
$customer1->setPerson("Obama","President",40);
$customer1->display();

?>

Display Result

Customer ID: 20311
Order Date: 04/14/2011
Cost: 20
Shipping Date: 04/15/2011
First Name: Obama
Last Name: President
Age: 40

PHP Extend Abstract Class from another class

  • An abstract class can inherit from another class.
  • In this tutorial, we have the DB class, and the MyDBConnect class has extended from the DB class.
  • On the other hand, the MySQL_db class has inherited from the MyDBConnect.

Code (DBcode.php)

<?php

	class DB {
		public function connectDB() {
			echo "Connect to DB \n";
		}
	}

	abstract class MyDBConnect extends DB {
		public abstract function ConsistentConnect();
	}

	class MySQL_db extends MyDBConnect{
		public function ConsistentConnect() {
			echo "This is a consistent connection to Mysql \n";
		}
	}

	$db_conn = new MySQL_db();
	$db_conn->ConsistentConnect();
	$db_conn->connectDB();
?>

Display Result

This is a consistent connection to Mysql
Connect to DB

PHP Interface Class

  • Interface has methods that the class must implement.
  • We only define methods without methods' content within the interface class.
  • And, all methods declared in the interface must be public.
  • When we use the interface we called it implement.
  • We must implement all the methods in the interface, if not we will get error message.
  • A single class may implement more than one interfaces.
  • Thus, we use the interface class to group unrelated class together.

Code (Activitee.php) Interface

  • We create an Activitee interface,
  • And, it contains three methods:setwork($work), getwork(), and message($msg).
  • All these methods must be declared and used by the class when the class implements this interface.
<?php
interface Activitee {
    //put your code here
    public function setwork($work);
    public function getwork();
    public function message($msg);
}
?>

Code (ActiviteeClass.php) (ActiviteeClass implement the interface)

  • We create the ActiviteeClass, and this class implements the Activitee interface.
  • Within the ActiviteeClass we declare all three methods that contains in the Activitee interface.
public function setwork($work) 
public function getwork()
public function message($msg)

=example code

<?php
require_once 'Activitee.php';
class ActiviteeClass implements Activitee {
  
    private $my_work,$massage;

    public function setwork($work) {
        $this->my_work = $work;
    }
    public function getwork(){
        return ($this->my_work);
    }
    public function  message($msg) {
        echo "This is my ". $msg . " !\n";
        echo "I work as ". $this->getwork() . "!\n";
        echo "this is my class massage " . $this->massage . "!\n";
    }
}
?>

Test the ActiviteeClass class (testActiviteeClass.php)

  • We have already created the interface and a class to implement this interface.
<?php
require_once 'ActiviteeClass.php';

$my_activities = new ActiviteeClass();
$my_activities->setwork("php oop programmer");
$my_activities->message("php and mysql");
?>

Display Result

This is my php and mysql !
I work as php oop programmer!
this is my class massage !
php oop programmer

Code (Prowork.php) interface

  • We declare two functions within the Prowork.php,
  • There are startwork($start) and stopwork($stop) function.
<?php
interface Prowork {
    public function startwork($start);
    public function stopwork($stop);
}
?>   

implements Activitee and Prowork interface(ActiviteeClass2.php)

  • This ActiviteeClass2 class implements two interface, Activitee and Prowork interfaces.
  • Also, ActiviteeClass2 must include all the methods from both interfaces.
public function setwork($work)
public function getwork()
public function message($msg)
public function startwork($start)
public function stopwork($stop)

Example code

<?php

//copyright w3cyberlearning.com and Sophal Chao, 2011, all rights reserved
require_once 'Activitee.php';
require_once 'Prowork.php';

class ActiviteeClass2 implements Activitee, Prowork {

    private $my_work,$massage;
    private $startwork, $stopwork;

    public function setwork($work) {
        $this->my_work = $work;
    }
    public function getwork(){
        return ($this->my_work);
    }
    public function  message($msg) {
        echo "This is my ". $msg . " !\n";
        echo "I work as ". $this->getwork() . "!\n";
        echo "this is my class massage " . $this->massage . "!\n";
        echo "Start work is ". $this->startwork . "\n";
        echo "Stop work is ". $this->stopwork . "\n";
    }
    public function  startwork($start) {
        $this->startwork = $start;
    }
    public function stopwork($stop) {
        $this->stopwork = $stop;
    }
}
?>

Test the ActiviteeClass2 class(testActiviteeClass2.php)

  • Again, we test this class to make sure it works correctly as we expected.
  • In the ActiviteeClass2 implements two other interfaces.
<?php

//copyright w3cyberlearning.com and Sophal Chao, 2011, all rights reserved
require_once 'ActiviteeClass2.php';

$my_activities2 = new ActiviteeClass2();
$my_activities2->setwork("php oop programmer");
$my_activities2->startwork("starting work");
$my_activities2->stopwork("stoping work");
$my_activities2->message("php and mysql");

?>

PHP Adapter Class

  • Adapter class is a design pattern that we normally use when we can't modify the original class.
  • We adapt the original class to a new method as needed.
  • Generally, we use the adapter pattern when we want to make the incompatible class to work togather.
  • The adapter class is also called wrapper pattern or simply wrapper.

Code (Customer.php)

  • We have demonstrated how to use interface and abstract in the Customer class.
  • The Customer class contains two attributes: name and address.
  • This Customer class implements the Address interface, and extends the Person abstract class.
<?php

abstract class Person {
	abstract public function setName($n);
	abstract public function getName();
}

interface Address {
	public function setAddress($address);
	public function getAddress();
}

class Customer extends Person implements Address  {
	protected $name;
	protected $address;

	public function setAddress($address) {
		$this->address = $address;
	}
	public function getAddress() {
		return ($this->address);
	}

	public function setName($name) {
		$this->name = $name;
	}
	public function getName() {
		return ($this->name);
	}

	public function __construct($name, $address) {
		$this->setAddress($address);
		$this->setName($name);
	}
}
?>

Code (OrderItem.php)

  • OrderItem class is a simple class which has three attributes: item_name, item_quantity and cost
<?php
//copyright w3cyberlearning.com and Sophal Chao, 2011, all rights reserved

class OrderItem {
	protected $item_name;
	protected $item_quantity;
	protected $cost;

	public function __construct($item_name, $item_quantity, $t_cost) 		{
		$this->item_name = $item_name;
		$this->item_quantity = $item_quantity;
		$this->cost = $t_cost;
	}
	public function getName() {
		return $this->item_name;
	}
	public function getQuantity() {
		return $this->item_quantity;
	}
	public function getCost() {
		return $this->cost;
	}
}
?>

Code (CustomerOrderAdapter.php) (adapter)

  • In the following example. We have the CustomerOrderAdapter adapter class.
  • This class takes in the instance of Customer and OrderItem classes.
  • In the getOrderDetail() method, its get the methods from both the Customer and OrderItem classes as its own.
<?php

//copyright w3cyberlearning.com and Sophal Chao, 2011, all rights reserved
require_once 'Customer.php';
require_once 'OrderItem.php';

class CustomerOrderAdapter {
	private $order;
	private $customer ;

	public function __construct(OrderItem $item, Customer $customer1) {
		$this->order = $item;
		$this->customer = $customer1;
	}
	public function getOrderDetail(){
	   return "Order Name:     "  . $this->order->getName()   	 . "\n".
		"Quantity:       "  . $this->order->getQuantity() . "\n".
		"Each Item Cost: "  . $this->order->getCost()     . "\n".
		"Total Cost:     "  . ($this->order->getCost() * $this->order->getQuantity()) . "\n" .
		"Customer Name:  "  . $this->customer->getName() . "\n" .
		"Address:	"  . $this->customer->getAddress() . "\n";
	}
}

$customer1 = new Customer("Johnny","403 Main Str, Box 1544, Houston Tx 71003 USA");
$order_infor = new OrderItem("Advanced PHP OOP Book",2,40);

$customer_order_detail = new CustomerOrderAdapter($order_infor, $customer1) ;

echo $customer_order_detail->getOrderDetail();
?>

Display Result

Order Name: 	Advanced PHP OOP Book
Quantity:	2
Each Item Cost: 40
Total Cost:	80
Customer Name:  Johnny
Address:	403 Main Str, Box 1544, Houston Tx 71003 USA
Navigation
Web
SQL
MISC
References