Oops
Oops
WB - Chhaya Gupta
What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform operations on
the data, while object-oriented programming is about creating objects that contain both data
and functions.
Object-oriented programming has several advantages over procedural programming:
•OOP is faster and easier to execute
•OOP provides a clear structure for the programs
•OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to
maintain, modify and debug
•OOP makes it possible to create full reusable applications with less code and shorter
development time
WB - Chhaya Gupta
Define a Class
A class is defined by using the class keyword, followed by the name of the class and a pair of
curly braces ({}). All its properties and methods go inside the braces:
Syntax
<?php
class Fruit {
// code goes here...
}
?>
Below we declare a class named Fruit consisting of two properties ($name and $color) and two
methods set_name() and get_name() for setting and getting the $name property:
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
Note: In a class, variables are called properties and functions are called methods!
WB - Chhaya Gupta
Define Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has
all the properties and methods defined in the class, but they will have different property values.
Objects of a class is created using the new keyword.
<!DOCTYPE html>
<html>
<!DOCTYPE html> <body>
<html> In the example below, <?php
<body> we add two more class Fruit {
<?php methods to class Fruit, // Properties
class Fruit {
// Properties
for setting and getting public $name;
the $color property: public $color;
public $name;
public $color; // Methods
function set_name($name) {
// Methods $this->name = $name;
function set_name($name) { }
$this->name = $name; function get_name() {
} return $this->name;
function get_name() { }
return $this->name; function set_color($color) {
} $this->color = $color;
} }
$apple = new Fruit(); function get_color() {
$banana = new Fruit(); return $this->color;
$apple->set_name('Apple'); }
$banana->set_name('Banana'); }
$apple = new Fruit();
echo $apple->get_name(); $apple->set_name('Apple');
echo "<br>"; $apple->set_color('Red');
echo $banana->get_name(); echo "Name: " . $apple->get_name();
?> echo "<br>";
</body> echo "Color: " . $apple->get_color();
</html> ?></body></html>
WB - Chhaya Gupta
PHP - The $this Keyword
The $this keyword refers to the current object, and is only available inside methods.
<?php So, where can we change the value of the $name property? There
class Fruit { are two ways:
public $name; 1. Inside the class (by adding a set_name() method and use
} $this):
$apple = new Fruit();
?> 2. Outside the class (by directly changing the
property value):
<!DOCTYPE html>
<html> <!DOCTYPE html>
<body> <html>
<?php <body>
class Fruit { <?php
class Fruit {
public $name;
public $name;
function set_name($name) { }
$this->name = $name; $apple = new Fruit();
} $apple->name = "Apple";
}
$apple = new Fruit(); echo $apple->name;
$apple->set_name("Apple"); ?></body></html>
echo $apple->name;
?></body></html>
WB - Chhaya Gupta
PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?></body></html>
WB - Chhaya Gupta
PHP - Access Modifiers
Properties and methods can have access modifiers which control where they can be accessed.
There are three access modifiers:
•public - the property or method can be accessed from everywhere. This is default
•protected - the property or method can be accessed within the class and by classes derived
from that class
•private - the property or method can ONLY be accessed within the class
In the following example we have added three different access modifiers to three properties
(name, color, and weight). Here, if you try to set the name property it will work fine (because
the name property is public, and can be accessed from everywhere). However, if you try to
set the color or weight property it will result in a fatal error (because the color and weight
property are protected and private):
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>
WB - Chhaya Gupta
In the next example we have added access modifiers to two functions.
Here, if you try to call the set_color() or the set_weight() function it will
result in a fatal error (because the two functions are considered protected
and private), even if all the properties are public:
<?php
class Fruit {
public $name;
public $color;
public $weight;
$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>
WB - Chhaya Gupta
PHP - The __construct Function
A constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function when you create
an object from a class.
Notice that the construct function starts with two underscores (__)!
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<?php <?php
class Fruit { class Fruit {
public $name; public $name;
public $color; public $color;
The example below has a __construct() function that is automatically called when you create an
object from a class, and a __destruct() function that is automatically called at the end of the
script:
<!DOCTYPE html>
<html>
<!DOCTYPE html> <body>
<html> <?php
<body> class Fruit {
<?php // Properties
class Fruit { var $name;
public $name; var $color;
public $color;
// Methods
function __construct($name) { function __construct($name, $color) {
$this->name = $name; $this->name = $name;
} $this->color = $color;
function __destruct() { }
echo "The fruit is {$this->name}."; function __destruct() {
} echo "The fruit is {$this->name} and the color is
} {$this->color}.";
$apple = new Fruit("Apple"); }
?></body></html> }
$apple = new Fruit("Apple", "red");
?></body></html>
WB - Chhaya Gupta
PHP - What is Inheritance?
Inheritance in OOP = When a class derives from another class.
The child class will inherit all the public and protected properties and methods from the parent
class. In addition, it can have its own properties and methods.
An inherited class is defined by using the extends keyword.
<!DOCTYPE html>
<html>
<body>
Example Explained
<?php
The Strawberry class is
class Fruit {
inherited from the Fruit
public $name;
class.
public $color;
This means that the
public function __construct($name, $color) {
Strawberry class can use
$this->name = $name;
the public $name and
$this->color = $color;
$color properties as well
}
as the public
public function intro() {
__construct() and intro()
echo "The fruit is {$this->name} and the color is {$this->color}.";
methods from the Fruit
}
class because of
}
inheritance.
// Strawberry is inherited from Fruit
The Strawberry class also
class Strawberry extends Fruit {
has its own method:
public function message() {
message().
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?></body></html> WB - Chhaya Gupta
PHP - Inheritance and the Protected Access Modifier
In the previous chapter we learned that protected properties or methods can be accessed
within the class and by classes derived from that class. What does that mean?
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
public $name;
public $color; we see that if we try to call
public function __construct($name, $color) { a protected method (intro()) from
$this->name = $name; outside the class, we will receive
$this->color = $color; an error. public methods will work
} fine!
protected function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
// Try to call all three methods from outside class
$strawberry = new Strawberry("Strawberry", "red"); // OK.
__construct() is public
$strawberry->message(); // OK. message() is public
$strawberry->intro(); // ERROR. intro() is protected
?></body></html>
WB - Chhaya Gupta
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) { we see that all works fine! It is because
$this->name = $name; we call the protected method (intro())
$this->color = $color; from inside the derived class
}
protected function intro() {
echo "The fruit is {$this->name} and the color is
{$this->color}.";
}
}
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
// Call protected function from within derived class -
OK
$this -> intro();
}
}
$strawberry = new Strawberry("Strawberry",
"red"); // OK. __construct() is public
$strawberry->message(); // OK. message() is public and
it calls intro() (which is protected) from within the
derived class
?></body></html> WB - Chhaya Gupta
PHP - Overriding Inherited Methods
Inherited methods can be overridden by redefining the methods (use the same name) in the
child class.
Look at the example below. The __construct() and intro() methods in the child class
(Strawberry) will override the __construct() and intro() methods in the parent class (Fruit):
<!DOCTYPE html>
<html>
<body>
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
class Strawberry extends Fruit {
public $weight;
public function __construct($name, $color, $weight) {
$this->name = $name;
$this->color = $color;
$this->weight = $weight;
}
public function intro() {
echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight} gram.";
}
}
$strawberry = new Strawberry("Strawberry", "red", 50);
$strawberry->intro();
?></body></html> WB - Chhaya Gupta
PHP - The final Keyword
The final keyword can be used to prevent class inheritance or to prevent method overriding.
<!DOCTYPE html>
<html>
<body>
<?php
class Goodbye { <!DOCTYPE html>
const LEAVING_MESSAGE = "Thank you for visiting <html>
W3Schools.com!"; <body>
} <?php
echo Goodbye::LEAVING_MESSAGE; class Goodbye {
?> const LEAVING_MESSAGE = "Thank you for visiting
</body> W3Schools.com!";
</html> public function byebye() {
echo self::LEAVING_MESSAGE;
}
Or, we can access a constant from }
inside the class by using $goodbye = new Goodbye();
the self keyword followed by the $goodbye->byebye();
scope resolution operator (::) ?>
followed by the constant name, like </body>
here: </html>
WB - Chhaya Gupta
PHP - What are Abstract Classes and Methods?
Abstract classes and methods are when the parent class has a named method, but need its child
class(es) to fill out the tasks.
An abstract class is a class that contains at least one abstract method. An abstract method is a
method that is declared, but not implemented in the code.
An abstract class or method is defined with the abstract keyword:
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name,
$color);
abstract public function someMethod3() :
string;
}
?>
WB - Chhaya Gupta
When inheriting from an abstract class, the child class method must be
defined with the same name, and the same or a less restricted access
modifier. So, if the abstract method is defined as protected, the child class
method must be defined as either protected or public, but not private.
Also, the type and number of required arguments must be the same.
So, when a child class is inherited from an abstract class, we have the
following rules:
•The child class method must be defined with the same name and it
redeclares the parent abstract method
•The child class method must be defined with the same or a less restricted
access modifier
•The number of required arguments must be the same. However, the child
class may have optional arguments in addition
WB - Chhaya Gupta
<!DOCTYPE html>
<html>
<body>
<?php
// Parent class
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name; Example Explained
}
abstract public function intro() : string; The Audi, Volvo, and Citroen classes
}
// Child classes
are inherited from the Car class. This
class Audi extends Car { means that the Audi, Volvo, and
public function intro() : string {
return "Choose German quality! I'm an $this->name!"; Citroen classes can use the public
}
}
$name property as well as the public
class Volvo extends Car { __construct() method from the Car
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!"; class because of inheritance.
}
} But, intro() is an abstract method
class Citroen extends Car { that should be defined in all the child
public function intro() : string {
return "French extravagance! I'm a $this->name!"; classes and they should return a
} string.
}
// Create objects from the child classes
$audi = new audi("Audi");
echo $audi->intro();
echo "<br>";
$volvo = new volvo("Volvo");
echo $volvo->intro();
echo "<br>";
$citroen = new citroen("Citroen");
echo $citroen->intro();
?></body></html>
WB - Chhaya Gupta
<!DOCTYPE html>
<html>
<body>
<?php
abstract class ParentClass {
// Abstract method with an argument
abstract protected function prefixName($name);
}
class ChildClass extends ParentClass {
public function prefixName($name) {
if ($name == "John Doe") {
$prefix = "Mr.";
} elseif ($name == "Jane Doe") {
$prefix = "Mrs.";
} else {
$prefix = "";
}
return "{$prefix} {$name}";
}
}
$class = new ChildClass;
echo $class->prefixName("John Doe");
echo "<br>";
echo $class->prefixName("Jane Doe");
?></body></html>
WB - Chhaya Gupta
<!DOCTYPE html>
<html>
<body>
<?php
abstract class ParentClass {
// Abstract method with an argument
abstract protected function prefixName($name);
}
class ChildClass extends ParentClass {
// The child class may define optional arguments that is not in the parent's abstract method
public function prefixName($name, $separator = ".", $greet = "Dear") {
if ($name == "John Doe") {
$prefix = "Mr";
} elseif ($name == "Jane Doe") {
$prefix = "Mrs";
} else { Let's look at another example where
$prefix = ""; the abstract method has an
} argument, and the child class has two
return "{$greet} {$prefix}{$separator} {$name}";
} optional arguments that are not
} defined in the parent's abstract
$class = new ChildClass; method:
echo $class->prefixName("John Doe");
echo "<br>";
echo $class->prefixName("Jane Doe");
?></body></html>
WB - Chhaya Gupta
<!DOCTYPE html>
<html>
<body>
<?php
abstract class ParentClass {
// Abstract method with an argument
abstract protected function prefixName($name);
}
class ChildClass extends ParentClass {
// The child class may define optional arguments that is not in the parent's abstract method
public function prefixName($name, $separator = ".", $greet = "Dear") {
if ($name == "John Doe") {
$prefix = "Mr";
} elseif ($name == "Jane Doe") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$greet} {$prefix}{$separator} {$name}";
}
}
$class = new ChildClass;
echo $class->prefixName("John Doe");
echo "<br>";
echo $class->prefixName("Jane Doe");
?></body></html>
WB - Chhaya Gupta