0% found this document useful (0 votes)
42 views21 pages

Unit 3OOP

This document provides an overview of Object-Oriented Programming (OOP) in PHP, highlighting key concepts such as classes, objects, inheritance, encapsulation, and access modifiers. It explains the advantages of OOP over procedural programming, including code reusability and maintainability. Additionally, it covers advanced topics like static properties, constructors, destructors, abstract classes, interfaces, and introspection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views21 pages

Unit 3OOP

This document provides an overview of Object-Oriented Programming (OOP) in PHP, highlighting key concepts such as classes, objects, inheritance, encapsulation, and access modifiers. It explains the advantages of OOP over procedural programming, including code reusability and maintainability. Additionally, it covers advanced topics like static properties, constructors, destructors, abstract classes, interfaces, and introspection.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit 3

Object Oriented Programming


INTRODUCTION
• Procedural programming like C 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
PHP - What are 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 Object

Fruit Apple
Banana
Mango
Car Volvo
Audi
Toyota

• 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 • Define Objects :-Classes are nothing without objects!
using the class keyword, followed by We can create multiple objects from a class. Each object
the name of the class and a pair of has all the properties and methods defined in the class,
curly braces ({}). All its properties and but they will have different property values.
methods go inside the braces: • Objects of a class are created using the new keyword.
• Syntax
• In the example below, $apple and $banana are
<?php instances of the class Fruit:
class Fruit { • Declaration an object
// code goes here...
} • $object = new class
?> • Accessing Properties and Methods
$object->property_name
$object->method_name([arg,….])
• <?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 $banana->get_name();

• ?>
• PHP - The $this Keyword • 1. Inside the class (by adding a set_name()
• The $this keyword refers to the current object, method and use $this):
and is only available inside methods. • <?php
• Look at the following example: class stud {
public $name;
• <?php
function set_name($name) {
class stud {
$this->name = $name;
public $name;
}
}
}
$a1 = new stud();
$a1 = new stud();
?>
$a1->set_name(“Archna");
• So, where can we change the value of the $name
property? There are two ways: echo $a1->name;
?>
• 2. Outside the class (by directly changing the property value):
• <?php
class stud {
public $name;
}
$a1 = new stud();
$a1->name = "Archana";

echo $a1->name;
?>
• Static Property and Static Method • <?php

class demo_static
• Also to access methods in terms of a class rather than an object,
{
use static keyword any method declared as static is accessible
without the creation of an object. Static functions are associated static $count; //static property

with the class and not with an instance of the class. They are public static function updatecount()
permitted to access only static methods and static variables. { //static method

• Inside a class, you can refer to the static property using the self return self : : $count++;
keyword. }

• Syntax : self::static_var_name }

demo_static: :$count =1;

for($i=0; i<3; ++$i)

echo “ the value is : “ .demo_static: : updatecount();

?>

O/P :- This value is :1

This value is: 2

This value is :3
PHP - The __construct Function
• <?php
• A constructor allows you to initialize an class Student {
public $name;
object's properties upon creation of the public $class;
object.
function __construct($name,$class)
• If you create a __construct() function,
{
PHP will automatically call this function $this->name = $name;
when you create an object from a
$this->class = $class;
class. }
function get_name()
• Notice that the construct function
{
starts with two underscores (__)! echo "student name is:".$this->name;
• that using a constructor saves us from echo "<BR>student class is:".$this->class;
calling the set_name() method which }
}
reduces the amount of code: $stud_obj = new Student(“Seema“,”FYBCA”);
$stud_obj->get_name();
?>
O/P :-student name is:Seema
student class is:FYBCA
PHP - The __destruct Function
<?php
• A destructor is called when the object
class Student {
is destructed or the script is stopped or
exited. public $name;

• If you create a __destruct() function,


function __construct($name) {
PHP will automatically call this function
at the end of the script.
$this->name = $name;
}
• Notice that the destruct function starts
function __destruct() {
with two underscores (__)!
echo "The Student name is {$this->name}.";
• 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
$stud1 = new Student(“Seema");
script: ?>
O/P -Seema
PHP - Access Modifiers
<?php
• Properties and methods can have access modifiers class Student {
which control where they can be accessed. public $name;
protected $class1;
• There are three access modifiers:
private $rno;
• public - the property or method can be accessed }
from everywhere. This is default
$stud = new Student();
• protected - the property or method can be $stud->name = ‘Seema’; // OK
$stud->class1 = ‘FYBCA’; // ERROR
accessed within the class and by classes derived
$stud->rno = 5; // ERROR
from that class ?>
• private - the property or method can ONLY be In above example we have added three different access
accessed within the class modifiers to three properties (name, class, and rno).
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 class or rno
property it will result in a fatal error (because the class and
rno property are protected and private):
<?php

class Book {

/* Member variables */
• Output
private $price;

private $title; Title: PHP Basics


/*Constructor*/ Price: 380
function __construct(string $param1="PHP Basics", int $param2=380) {
Fatal error: Uncaught Error: Cannot access private
$this->title = $param1;
property
$this->price = $param2;

}
Book::$title in hello.php:31
public function getPrice() { Now, the getTitle() and getPrice() functions are public, able to
access the private member variables title and price. But, while
echo "Price: $this->price \n";
trying to display the title and price directly, an error is
} encountered as they are not public.
public function getTitle() {

echo "Title: $this->title \n;";

} }

$b1 = new Book();

$b1->getTitle();

$b1->getPrice();

echo "Title : $b1->title Price: $b1->price";

• ?>
PHP – Inheritance
<?php

class Book { public function dispebook() {


protected $price; /* Member variables */ echo "Title: $this->title Price: $this->price\n";
protected $title; echo "Format: $this->format \n";
public function getbook( $param1, $param2) } }
{ $eb = new ebook;
$this->title = $param1; $eb->getebook("PHP Fundamentals", 450, “PDF");
$this->price = $param2; $eb->dispebook();
} ?>
public function dispbook() {
• output
echo "Title: $this->title Price: $this->price \n";

} }
Title: PHP Fundamentals Price: 450
class ebook extends Book { Format: EPUB
private string $format;
• we use the Book class as the parent class. Here, we create an
public function getebook($param1, $param2, $param3) { ebook class that extends the Book class. The new class has an
$this->title = $param1; additional property – format (indicating ebook’s file format –
$this->price = $param2; EPUB, PDF, MOBI etc). The ebook class defines two new
$this->format = $param3; methods to initialize and output the ebbok data – getebook()
}
and dispebook() respectively.
• Final Method
• If you declare the method using final keyword in superclass /parent class, then subclass/ • In the derived class B, display( )function can’t be redefined
child class can’t override that method. Method should not be overridden due to security as it is declared as final in base class A so you will get error
reason. message.
• <?php
• Properties and constants cannot be declared final, only classes and methods may be
declared as final. class A {

• <?php private $message= “Hi”;

class A { final function display( ) {

private $message= “Hi”; echo $this->message;

final function display( ) }

{ }

echo $this->message; class B extends A {

} function displayB()

} {

class B extends A { echo “Hello”;

function display() } }

{ $obj = new B;

echo “Hello”; $obj ->display( );

} } $obj->displayB( );

?> ?>

• O/P : Fetal error : cannot override final method A : : display() • O/P :- Hi Hello
Abstract Class and Abstract Method
• 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:
• 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
<?php
abstract class A {
abstract function one( );
public function two( ) {
echo “Non-abstract method”;
}
}
class B extends A {
public function one ( )
{
echo “Abstract Function one “;
}
}
$obj = new B( );
$obj -> one( );
$obj -> two( );
?>
O/P – Abstract Function one
Non –abstract method
INTERFACES
• An interface allows the users to create programs, specifying the public methods that a class must implement.
Characteristics of an Interface :
• Interface is similar to a class except that it cannot contain code.
• An interface can define method names and arguments, but not the contents of the methods.
• All methods declared in an interface must be public.
• Any classes implementing an interface must implement all methods defined by the interface.
• A class can implement multiple interfaces.
• An interface is declared using the “interface” keyword.
• Interfaces can’t maintain non-abstract methods.
Advantages of an Interface
• It separates the implementation and defines the structure.
• It is used to define a generic template.
<?php
interface information {// Interface definition
public function displayname();
} • O/P
// Class definitions
• Atharv Sanjeev
class student implements information {
public function displayname() {
echo " Atharv";
}
}
class employee implements information {
public function displayname() {
echo " Sanjeev";
}
}
$stud = new student();
$emp = new employee();
$stud->displayname();
$emp->displayname();
?>
INTROSPECTION
• With introspection, you can write code that operates on any class or object. You don’t need to know which
methods or properties are defined when you write your code, instead you can discover that information at
runtime.
• Examining Classes :- 1) To determine whether a class exists, use the class_exists() function
Syntax :- $yes_no = class_exists(classname);
2) get_declared_classes() function, which returns an array of defined classes and you can verify the class name in
the returned array. Syntax :- $classes = get_declared_classes();
3) Get methods and properties that exist in a class.
Syntax :-$methods = get_class_methods(classname);
$properties = get_class_vars(classname);
4) Use get_parent_class() to find a class’s parent class name.
Syntax :- $superclass = get_parent_class(classname);
INTROSPECTION
• Examining an object :-
1)To get the class to which an object belongs, first check if it is an object using the is_object( ) function then get
the class with the get_class() function.
Syntax :- $yes_no = is_object(var);
$classname = get_class(object);
2) Before calling a method on an object, You can check that it exists using the method_exists() function:
Syntax :- $yes_no = method_exists(object, method);
3)get_object_vars( ) returns an array of properties that are set in an object.
Syntax :- $array = get_object_vars (object);
ENCAPSULATION
• In today’s technical world, maintaining privacy has become one of the demanding needs for the protection of
important data. Whenever data modified in one function affects the other functions, it causes a lot of problems in
any software. To overcome this problem, object-oriented programming in PHP uses the concept of
Encapsulation.
• A class is kind of a container or capsule, which contains properties and a set of methods to manipulate these
properties. This is called as Encapsulation. It binds together code and the data it manipulates.
• The variable or data of a class are hidden from any other class and can be accessed only through any member
function of that class. The data in a class is hidden from any other classes is called Data Hiding.
• PHP implements encapsulation, one of the important principles of OOP with access control keywords: public,
private and protected.
• Encapsulation refers to the mechanism of keeping the data members or properties of an object away from
the reach of the environment outside the class, allowing controlled access only through the methods or
functions available in the class.

You might also like