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

Unit 3 PHP

The document provides an overview of Object-Oriented Programming (OOP) in PHP, explaining its advantages over procedural programming, such as improved code structure and reusability. It covers key concepts including classes, objects, inheritance, access modifiers, constructors, destructors, and abstract classes, along with examples of their implementation. Additionally, it discusses the clone keyword and introspection functions available in PHP for examining object characteristics.

Uploaded by

kokanesanket24
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 3 PHP

The document provides an overview of Object-Oriented Programming (OOP) in PHP, explaining its advantages over procedural programming, such as improved code structure and reusability. It covers key concepts including classes, objects, inheritance, access modifiers, constructors, destructors, and abstract classes, along with examples of their implementation. Additionally, it discusses the clone keyword and introspection functions available in PHP for examining object characteristics.

Uploaded by

kokanesanket24
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

PHP 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

Classes and Objects


Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and
objects:

class
Fruit

objects
Apple

Banana

Mango

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and
behaviors from the class, but each object will have different values for the
properties.
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...
}
?>

<?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!

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 are created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:
Example
<?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();


$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

The $this Keyword


The $this keyword refers to the current object, and is only available
inside methods.
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>

We can change the value of the $name property.

There are two ways:


1. Inside the class (by adding a set_name() method and use $this):

Example
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");

echo $apple->name;
?>

2. Outside the class (by directly changing the property value):

<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";

echo $apple->name;
?>

instanceof
You can use the instanceof keyword to check if an object belongs to a specific
class:

Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
Constructor
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 (__)!

We see in the example below, that using a constructor saves us from calling the
set_name() method which reduces the amount of code:

Example
<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}

$apple = new Fruit("Apple");


echo $apple->get_name();
?>

Destructor
The __destruct Function
A destructor is called when the object is destructed or the script is stopped or
exited.
If you create a __destruct() function, PHP will automatically call this function
at the end of the script.

Notice that the destruct function starts with two underscores (__)!

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:

<?php
class Fruit {
public $name;
public $color;

function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}

$apple = new Fruit("Apple");


?>

Tip: As constructors and destructors helps reducing the amount of code, they
are very useful!

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
?>

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.

Let's look at an example:

<?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}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>

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?

Let's look at an example:

<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
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
?>

In the example above we see that if we try to call a protected method (intro())
from outside the class, we will receive an error.

Example
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
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 method 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
?>

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):

Example
<?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();
?>

The final Keyword


The final keyword can be used to prevent class inheritance or to prevent
method overriding.

The following example shows how to prevent class inheritance:

Example
<?php
final class Fruit {
// some code
}

// will result in error


class Strawberry extends Fruit {
// some code
}
?>

The following example shows how to prevent method overriding:

Example
<?php
class Fruit {
final public function intro() {
// some code
}
}

class Strawberry extends Fruit {


// will result in error
public function intro() {
// some code
}
}
?>

Class Constants
Class constants can be useful if you need to define some constant data within a
class.
A class constant is declared inside a class with the const keyword.

A constant cannot be changed once it is declared.

Class constants are case-sensitive. However, it is recommended to name the


constants in all uppercase letters.

We can access a constant from outside the class by using the class name
followed by the scope resolution operator (::) followed by the constant name,
like here:

Example
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
}

echo Goodbye::LEAVING_MESSAGE;
?>

Or, we can access a constant from inside the class by using the self keyword
followed by the scope resolution operator (::) followed by the constant name,
like here:

Example
<?php
class Goodbye {
const LEAVING_MESSAGE = "Thank you for visiting W3Schools.com!";
public function byebye() {
echo self::LEAVING_MESSAGE;
}
}

$goodbye = new Goodbye();


$goodbye->byebye();
?>

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:

Syntax
<?php
abstract class ParentClass {
abstract public function someMethod1();
abstract public function someMethod2($name, $color);
abstract public function someMethod3() : string;
}
?>

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. However, the child classes may have
optional arguments in addition.

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

Example
<?php
// Parent class
abstract class Car {
public $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function intro() : string;
}

// Child classes
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}

class Volvo extends Car {


public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}

class Citroen extends Car {


public function intro() : string {
return "French extravagance! I'm a $this->name!";
}
}

// 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();
?>

Clone Keyword
Create a copy of an object:

<?php
class MyClass {
public $color;
public $amount;
}

$obj = new MyClass();


$obj->color = "red";
$obj->amount = 5;
$copy = clone $obj;
print_r($copy);
?>

MyClass Object
(
[color] =>red
[amount] => 5
)

Definition and Usage


The clone keyword is used to create a copy of an object.

If any of the properties was a reference to another variable or object, then only
the reference is copied. Objects are always passed by reference, so if the
original object has another object in its properties, the copy will point to the
same object. This behavior can be changed by creating a __clone() method in
the class.

Create a copy of an object which has a reference:

<?php
class MyClass {
public $amount;
}

// Create an object with a reference


$value = 5;
$obj = new MyClass();
$obj->amount = &$value;

// Clone the object


$copy = clone $obj;

// Change the value in the original object


$obj->amount = 6;

// The copy is changed


print_r($copy);
?>
MyClass Object
(
[amount] => 6
)

Introspection in PHP:
Introspection in PHP offers the useful ability to examine an object's characteristics,
such as its name, parent class (if any) properties, classes, interfaces, and methods.
PHP offers a large number of functions that you can use to accomplish the task.
The following are the functions to extract basic information about classes such as
their name, the name of their parent class and so on.
In-built functions in PHP Introspection :

Function Description
class_exists() Checks whether a class has been defined.
et_class() Returns the class name of an object.
get parent_class() Returns the class name of a Return object's parent class.
is_subclass_of() Checks whether an object has a given parent class.
get_declared_classes() Returns a list of all declared classes.
get_class_methods() Returns the names of the class methods.
get_class_vars() Returns the default properties of a class
interface_exists() Checks whether the interface is defined.
method_exists() Checks whether an object defines a method.

<?php

if(class_exists('cwipedia'))
{
$ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{
echo "Not exist";
}

?>
Output: Not exist

<?php
classcwipedia
{
//decl
}
if(class_exists('cwipedia'))
{
$ob=new cwipedia();
echo "This is cwipedia.in";
}
else
{
echo "Not exist";
}

?>

Output: This is cwipedia.in

Serialization in PHP:
Serialization is a technique used by programmers to preserve their working
data in a format that can later be restored to its previous form.

Serializing an object means converting it to a byte stream representation


that can be stored in a file.

Serialization in PHP is mostly automatic, it requires little extra work from


you, beyond calling the serialize() and unserialize() functions.

Serialize():
The serialize() converts a storable representation of a value.
The serialize() function accepts a single parameter which is the data we
want to serialize and returns a serialized string
A serialize data means a sequence of bits so that it can be stored in a file, a
memory buffer, or transmitted across a network connection link. It is useful
for storing or passing PHP values around without losing their type and
structure.

Syntax:
serialize(value);
unserialize():
unserialize() can use string to recreate the original variable values i.e.
converts actual data from serialized data.

Syntax:
unserialize(string);

Example:

<?php
$a=array('Shivam','Rahul','Vilas');
$s=serialize($a);
print_r($s);
$s1=unserialize($s);
echo "<br>";
print_r($s1);
?>
Output:
a:3:{i:0;s:6:"Shivam";i:1;s:5:"Rahul";i:2;s:5:"Vilas";}
Array ( [0] =>Shivam [1] => Rahul [2] => Vilas )

You might also like