06.Object-Oriented Programming in PHP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Server Side Internet

Programming
Object-Oriented Programming in PHP
Object-Oriented Programming
- Models a program into objects
- Use “class” to create a template for objects
- Four pillars of OOP:
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Reasons of adapting OOP
- Clear and more structured application
- Prevent repetition in creating parts of program (DRY → Don’t Repeat Yourself)
- Create reusable application
Class and Object
- Class → template for objects
- Objects → instance of classes
Attributes and Methods
- Attributes → identity / characteristic that is inside a class
- Methods → behavior / activity that could be done by a class

Example: we could model a student as a class

Attributes of Student: name, ID, major, grade

Methods of Student: study, payTuition, academicLeave


Abstraction
- Abstraction is the process of hiding internal details of an application
- Define things in a simpler term
- Create a boundary between programs

Example: What has two feet, two wings, and a beak?


Example: character.php
<?php
class Character {
// define attributes
public $name;
public $health;

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

function getHealth() {
return $this->health;
}

function getHit($damage=1) {
$this->health -= $damage;
}
}
?>
Example: main.php
<?php
require_once("character.php");
// create object
$warrior = new Character();

// set attributes
$warrior->name = "Baraka";
$warrior->health = 100;

// call the object method


$warrior->getHit(30);
echo("{$warrior->getName()} health is now {$warrior->getHealth()}");
?>
Note about this approach
- Need to add the attributes one by one
- Could be defined using a more subtle approach: constructor
- Adding constructor with parameters will help
Constructor and Destructor
Constructor → to construct / create object from a class

Destructor → to clean up data after the object is instantiated and used


Example: character.php
<?php
class Character {
// define attributes
public $name;
public $health;

function __construct($name, $health=100) {


$this->name = $name;
$this->health = $health;
}
Notice we directly set
function __destruct() { attributes inside constructor
echo("Object cleaned: {$this->name}<br/>");
}

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

function getHealth() {
return $this->health;
}

function getHit($damage=1) {
$this->health -= $damage;
}
}
?>
Example: main.php (changed)
<?php
require_once("character.php");
// create objects We could instantiate objects
$warrior = new Character("Baraka"); from class easily now
$ninja = new Character("Sub Zero", 300);

// call the object method


$warrior->getHit(30);
$ninja->getHit(70);
echo("{$warrior->getName()}. Health: {$warrior->getHealth()}<br/>");
echo("{$ninja->getName()}. Health: {$ninja->getHealth()}<br/>");
?>
Abstract Class
- Used as the template for another classes
- Same as class, but cannot be instantiated into objects
- Cannot use new keyword

P.S: Talk about this later in the discussion


Example: character.php with abstract class
<?php
abstract class Character {
private $name;
private $health;

abstract public function getName();


abstract public function getHealth();
abstract public function getHit($damage);
}

$myChar = new Character(); // ERROR!


?>

You cannot create object from abstract class


Accessing Static Attributes / Functions
- Using static keyword and “::”
- Attributes and Methods with static could be accessed without creating object
- We could use this anywhere in the program
Example: accessing static attributes / methods
<?php
class Character {
public static $characterCount = 0;
public $name;
public $health;

public function __construct($name, $health=100) {


$this->name = $name;
$this->health = $health;
Character::$characterCount++;
}
}

$warrior = new Character("Warrior", 100);


$ninja = new Character("Ninja", 90);
echo(Character::$characterCount);
?>
Encapsulation
Hide information from outside. As in other languages, we have several access modifiers:

1. Public: property or method can be accessed from everywhere. This is default


2. Protected: property or method can be accessed within the class and by classes
derived from that class
3. Private: property or method can ONLY be accessed within the class
Example: character.php with encapsulation
<?php
class Character {
// private attributes cannot be accessed outside!
private $name;
private $health;

public function __construct($name, $health=100) {


$this->name = $name;
$this->health = $health;
}

public function getName() {


return $this->name;
}

private function getHealth() {


return $this->health;
}

public function getHit($damage=1) {


$this->health -= $damage;
}
}
?>
main.php

<?php
require_once("character.php");
// create object
$warrior = new Character("Baraka");
$ninja = new Character("Sub Zero", 300);

// call the object method


$warrior->getHit(30);
$ninja->getHit(70);

// error, accessing private attributes/methods


echo($warrior->name);
echo($ninja->getHealth());
?>
Overcoming Issues
- Use the concept of accessor and mutator to change or get data
- Accessor → to access or get a data
- Mutator → to mutate/change or set data
- Sometimes people call it setter and getter methods
Example: character.php with setter and getter methods
<?php
class Character {
private $name;
private $health;

public function __construct($name, $health=100) {


$this->name = $name;
$this->health = $health;
}

public function getName() {


return $this->name;
}

public function setName($name) {


$this->name = $name;
}

// ... create the same for health


// ... other methods as previous
}
?>
main.php calling the character class with getter and setter methods

<?php
require_once("character.php");
// create object
$warrior = new Character("Baraka");
$warrior->setName("Kung Lao");
echo("Change name to {$warrior->getName()}");
?>
Inheritance
- Inheritance lets us to reuse a part of a program
- Inheritance makes program creation easier
- Has a parent-child relationship
- Parent class is called as the “super” class
- Children class is called as the “sub” class
- If a class “inherits” from a superclass, every public / protected attributes and
methods are accessible
- By doing this, we do not need to re-create a certain part of our program
Case
In a game, we have multiple options for weapons like sword, axes, guns, bows, etc

Each weapon will have several similar characteristics such as:

1. Name
2. Damage

We could utilize the inheritance to simulate how the weapon is constructed in a game

Create these files:

1. weapon.php → contains the base class for the weapon


2. sword.php → contains the inheriting class
3. index.php → contains the main logic
Example: weapon.php
<?php
class Weapon {
protected $name;
protected $damage;
public function __construct($name="", $damage=0) {
$this->name = $name;
$this->damage = $damage;
}
public function setName($name) {
$this->name = $name;
}
public function setDamage($damage) {
$this->damage = max($damage, 0);
}
public function getName() {
return $this->name;
}
public function getDamage() {
return $this->damage;
}
public function getInfo() {
echo("Name: {$this->name}<br/>");
echo("Damage: {$this->damage}<br/>");
}
}
?>
Example: sword.php
<?php
require_once("weapon.php");

class Sword extends Weapon {


private $sharpness;

public function __construct($name, $damage, $sharpness=0) {


parent::__construct($name, $damage);
$this->sharpness = $sharpness;
}

public function setSharpness($sharpness) {


$this->sharpness = $sharpness;
}

public function getSharpness() {


return $this->sharpness;
}

public function getInfo() {


parent::getInfo();
echo("Sharpness: {$this->sharpness}<br/>");
}
}
?>
Example: index.php
<?php
require_once("sword.php");
$saber = new Sword("Saber", 100, 100);
echo($saber->getInfo());

$saber->setDamage(200);
$saber->setSharpness(1000);
echo($saber->getInfo());
?>
Polymorphism
- Polymorphism means: many shapes
- Ability of an object to have different implementations but sharing the same interface
(in this case, functions / methods)
- Polymorphism could be simulated by using abstract class / interface
- Using the concept of method overriding / overloading
- Overriding → replace the implementation of the method / function with the same name
- Overloading → replace the implementation of the method / function with additional parameters
Overriding vs Overloading
Overloading: Overriding:

- Known as Static / Compile-Time - Known as Dynamic / Run-Time


polymorphism polymorphism
- Methods are located in the same class, - Methods are located in the different
with same name but different class (children) with same name and
parameters same parameters

*note: in PHP, overloading could not be


done as easily as in other languages
Let’s have a case
Still using our game example. Think about this:

- What if we want a projectile (shooting) weapon?


- Mainly two types of projectile: guns and bows
- Both guns and bows could do something called as “shoot”
- Bow could shoot only 1 arrow or multiple arrows
- Guns could shoot only 1 bullet or burst

Knowing this let’s design the classes!


Example: projectile.php
<?php
abstract class Projectile {
protected $ammo;

abstract public function getAmmo();


abstract public function setAmmo($ammo);
abstract public function shoot();
}
?>
Example: bow.php (left) and gun.php (right)
<?php <?php
require_once('projectile.php'); require_once('projectile.php');

class Bow extends Projectile { class Gun extends Projectile {


public function getAmmo() { public function getAmmo() {
return $this->ammo; return $this->ammo;
} }

public function setAmmo($ammo) { public function setAmmo($ammo) {


$this->ammo = $ammo; $this->ammo = $ammo;
} }

public function shoot() { public function shoot() {


// decrement ammo by 1 // decrement ammo by 2
$this->ammo--; $this->ammo -= 2;
} }
} Notice how the method is the same. }
?> This is called as overriding ?>
Example: main.php
<?php
require('bow.php');
require('gun.php');

$bow = new Bow;


$gun = new Gun;

$bow->setAmmo(3);
$gun->setAmmo(100);
Take a look how we define the
$bow->shoot();
functions with same name, but for a
for ($i = 1; $i <= 10; $i++) { totally different object
$gun->shoot();
}

echo("Bow Ammo: {$bow->getAmmo()}<br/>");


echo("Gun Ammo: {$gun->getAmmo()}<br/>");

?>
PHP Namespace
- Qualifiers to organize files in a project / application
- Using namespace, we could differentiate classes with same name but located in
different folder

Example of a case:

In your computer, you could have these conditions

1. C:\xampp\htdocs\Office\employee.php
2. C:\xampp\htdocs\Factory\employee.php

Question: When you create a project, how would be be able to differentiate between
employee.php in Office or in Factory folder?
Example: employee.php inside Factory folder
<?php
namespace Factory; Add namespace at the beginning of
the file to show this is in the area /
class Employee { domain of Factory
private $name;

public function __construct($name) {


$this->name = $name;
}

public function getName() {


return $this->name;
}

public function getSalaryInfo() {


return "Daily";
}
}
?>
Example: employee.php inside Office folder
<?php
namespace Office;

class Employee {
private $name;

public function __construct($name) {


$this->name = $name;
}

public function getName() {


return $this->name;
}

public function getSalaryInfo() {


return "Monthly";
}
}
?>
Example: main.php

<?php
require("Factory/employee.php");
require("Office/employee.php");

$empOffice = new \Office\Employee("John");


$empFactory = new \Factory\Employee("Bob");

echo($empOffice->getName() . "<br/>");
echo($empOffice->getSalaryInfo() . "<br/>");

echo($empFactory->getName() . "<br/>");
echo($empFactory->getSalaryInfo() . "<br/>");
?>
Exercise
Create a class that simulates the employee data in a company.

An employee has attributes:

1. Name
2. ID
3. Gender
4. Salary

An employee could:

1. Get his/her salary


2. Get his/her data (name, ID and Gender)
3. Be given a bonus (using method)
References
https://www.w3schools.com/php/php_oop_what_is.asp

https://www.w3schools.com/php/php_oop_classes_objects.asp

https://www.w3schools.com/php/php_oop_inheritance.asp

https://www.w3schools.com/php/php_oop_classes_abstract.asp

https://www.w3schools.com/php/php_oop_static_methods.asp

https://www.php.net/manual/en/language.namespaces.rationale.php

https://www.codecademy.com/resources/blog/what-is-inheritance/

https://stackify.com/oop-concept-polymorphism/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy