0% found this document useful (0 votes)
26 views

OOP in PHP

Uploaded by

Ayubu Zuberi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

OOP in PHP

Uploaded by

Ayubu Zuberi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

OOP in PHP

CP 311: Internet programming and


applications II

Steve ‘241(CIVE)
Objectives
• Learn about OOP in PHP

2
Introduction
• Object-Oriented Programming (OOP) is a type of programming
added to php5 that makes building complex, modular and
reusable web applications that are much easier.

Advantages of OOP
1. OOP is faster and easier to execute
2. OOP provides a clear structure for the programs
3. OOP helps to keep the PHP code DRY "Don't Repeat
Yourself", and makes the code easier to maintain, modify and
debug
4. OOP makes it possible to create full reusable applications with
less code and shorter development time. 3
Key OOP Concepts
• Class: Template for creating objects.
• Object: Instance of a class.
• Member Variable: Attributes of an object.
• Member Function: Functions inside a class that operates on
object data.
• Inheritance: Deriving a class from another.
• Polymorphism: Functions behaving differently based on input.
• Encapsulation: Grouping variables and functions in a single
entity.
• Abstraction: Hiding implementation details.

4
Defining Classes in PHP
• Classes are the blueprints for php objects. One of the big
differences between functions and classes is that a class
contains both data.

<?php
class Person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name;
}
} 5
?>
Static properties and methods
• It is not always necessary to instantiate an object to access the
properties or methods of a class.
• A class can also have static methods and properties that are
bound to the class, rather than the object.
• To access a static method or a static property, we will use the
scope resolution operator (::).
• To create a static property or static method, we will append the
static keyword ahead of the variable.
• self::funct() vs Person::funct()

6
Static properties and methods
<?php
class Foo {
public static $my_static = 'foo’;
public function staticValue() {
return self::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
?> 7
Set an objects properties
<?php require("class_lib.php"); ?>
</head>
<body>
<?php
$stefan = new person();
$jimmy = new person();
$stefan->set_name("Stefan Mischook");
$jimmy->set_name("Nick Waddles");

echo "Stefan's full name: " . $stefan->get_name();!


echo "Nick's full name: " . $jimmy->get_name();
?>
</body>
8
</html>
Constructors
• All objects can have a special built-in method called a
'constructor'. Constructors allow you to initialize your
object's properties (translation: give your properties
values) when you instantiate (create) an object.
<?php
class Person {
private $name;
// Constructor
public function __construct($persons_name) {
$this->name = $persons_name;
}
public function setName($new_name) {
$this->name = $new_name;
}
public function getName() {
return $this->name;
} 9
}
?>
Object with Constructor
<?php
require ("class_lib.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Person Class Example</title>
</head>
<body>
<?php
$stefan = new Person("Stefan Mischook");
echo "Stefan's full name: " . $stefan->getName();
?>
</body>
</html> 10
Encapsulation
• One of the fundamental principles in OOP is 'encapsulation'.
The idea is that you create cleaner better code, if you restrict
access to the data structures (properties) in your objects.

11
Encapsulation
<?php
class Person {
public $name;
public $height;
protected $social_insurance;
private $pinn_number;

// Constructor to initialize the person's name


public function __construct($persons_name) {
$this->name = $persons_name;
}

// Private method to get the PIN number


private function getPinnNumber() {
return $this->pinn_number;
}
} 12
?>
Inheritance
• Inheritance is commonly used when we want to create classes
that would reuse the properties and/or class methods that are
similar to existing classes.
• It is common to have this abstract high - level functionality in a
class that is referred to as the base or the parent class and then
group this functionality into multiple different subclasses or
child classes that would use properties or methods from that
base class.

13
<?php
// Parent class 'Person'
class Person {
protected $name;
// Constructor to initialize the person's name
public function __construct($person_name) {
$this->name = $person_name;
}
// Method to set the name // Child class 'Employee' extends 'Person'
public function setName($new_name) { class Employee extends Person {
$this->name = $new_name; // Constructor to initialize the employee's name
} public function __construct($employee_name) {
// Method to get the name // Call the parent class constructor
public function getName() { parent::__construct($employee_name);
return $this->name; }
} }
}
?>

14
Inheritance
<?php include("class_lib.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP OOP Example</title>
</head>
<body>
<?php
// Using our PHP objects in our PHP pages
// Create a new Person object
$stefan = new Person("Stefan Mischook");
echo "Stefan's full name: " . $stefan->getName() . "<br>";
// Create a new Employee object
$james = new Employee("Johnny Fingers");
echo "Employee's full name: " . $james->getName();
?>
</body>
</html> 15
Polymorphism
• Polymorphism comes from Greek words that mean
“many forms,” and it refers to the ability of objects
to take on many forms or the ability to treat
different objects as instances of the same class
through a common interface.
• Types of Polymorphism
• Compile-Time Polymorphism (Static
Polymorphism):
• This type of polymorphism is resolved at compile-time.
• Method Overloading and Operator Overloading
are common examples.
• Run-Time Polymorphism (Dynamic
Polymorphism): 16
• This type of polymorphism is resolved at runtime.
• Method Overriding: A subclass can provide a specific
implementation of a method that is already defined in
Run-Time Polymorphism
<?php
class Animal {
public function makeSound() {
echo "Some generic animal sound\n";
}
// Using polymorphism
$animal1 = new Dog();
}
$animal2 = new Cat();
class Dog extends Animal {
public function makeSound() {
$animal1->makeSound();
echo "Woof! Woof!\n";
$animal2->makeSound();
}
}
?>
class Cat extends Animal {
public function makeSound() {
echo "Meow! Meow!\n";
}
}
17
Compile-Time Polymorphism
<?php
class Calculator {
// Add method with optional parameters
public function add($a = 0, $b = 0, $c = 0) {
return $a + $b + $c;
}
}
$calc = new Calculator();
// Adding two numbers
echo $calc->add(2, 3); // Outputs: 5

// Adding three numbers


echo $calc->add(1, 2, 3); // Outputs: 6

// Adding one number (remaining ones will be treated as 0)


echo $calc->add(10); // Outputs: 10
?> 18
// Define the person class
class Person { // Define the employee class that extends person
var $name; class Employee extends Person {
// Constructor function
__construct($persons_name) { // Override the set_name method for employee
$this->name = $persons_name; protected function set_name($new_name) {
}
if ($new_name == "Stefan Lamp") {
// Getter method to retrieve the name
$this->name = $new_name;
function get_name() {
return $this->name;
} else if ($new_name == "Johnny Fingers") {
} parent::set_name($new_name);
// Protected method to set the name }
protected function set_name($new_name) }
{
if ($new_name != "Jimmy Two Guns") { // Constructor to initialize the employee's name
$this->name = function __construct($employee_name) {
strtoupper($new_name);
}
$this->set_name($employee_name);
} }
} } 19
Final Keyword
• PHP 5 introduces the final keyword, which prevents child classes
from overriding a method by prefixing the definition with final. If
the class itself is being defined final then it cannot be extended.
• The following example results in Fatal error: Cannot override final
method.
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called<br>";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called<br>";
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called<br>";
20
}
}
?>
Abstract Classes
• An abstract class cannot be instantiated, only inherited. You
declare an abstract class with the keyword abstract.
• When inheriting from an abstract class, all methods marked
abstract in the parent's class declaration must be defined by the
child; additionally, these methods must be defined with the
same visibility.

abstract class MyAbstractClass {


abstract function myAbstractFunction() {
}
}
21
Abstract Classes
abstract class Animal {
protected $name;

// Abstract method
abstract public function makeSound();

$dog = new Dog();


// Concrete method (can be inherited as is)
$dog->setName("Buddy");
public function setName($name) {
$dog->makeSound(); // Outputs: Woof!
$this->name = $name;
}
}

class Dog extends Animal {


public function makeSound() {
echo "Woof!<br>";
}
} 22
Abstract Classes
• It is a class that has at least one abstract method.
• Use of keyword abstract.
• It can inherit 1 or more interfaces.
• It can not inherit more than 1 abstract class.
• Abstract class can not inherit from non abstract class
• Abstract method only name & arguments no other code.

23
Interface
• Interfaces are similar to abstract classes. The
differences between interfaces and abstract
classes are:
• Interfaces cannot have properties, while abstract
classes can
• All interface methods must be public, while abstract
class methods is public or protected
• All methods in an interface are abstract, so they
cannot be implemented in code and the abstract
keyword is not necessary
• Classes can implement an interface while inheriting
from another class at the same time
• Interfaces allow for multiple inheritance, 24
meaning a class can implement more than one
interface.
Interface
interface Animal {
public function makeSound();
}
interface CanFly {
public function fly();
} $bird = new Bird();
$bird->makeSound(); // Outputs: Chirp!
$bird->fly(); // Outputs: Flying high!
class Bird implements Animal, CanFly {
public function makeSound() {
echo "Chirp!<br>";
}
public function fly() {
echo "Flying high!<br>";
}
} 25
Concrete Class
• The class which implements an interface called concrete class.
• It must implement all methods defined in an interface.
• It can be inherited by another class, but not an abstract class.
• It can implement any no. of interfaces

26

You might also like