UNIT – IV Chapter 7 Introduction to OOPS
7.1 Class, Objects, Constructor, Destructor
7.2 Access method and properties using $this variable
7.3 Public, private, protected properties and methods
7.4 Static properties and method
7.5 Inheritance & code reusability
7.6 Polymorphism
7.7 Parent:: & self:: keyword
7.8 Instanceof operator
7.9 Interface
Introduction to OOPS:
PHP is a server-side scripting language, mainly used for web development but also used as a
general-purpose programming language. Object-Oriented Programming (PHP OOP), is a type of
programming language principle added to php5, that helps in building complex, reusable web
applications.
The Object Oriented concepts in PHP are:
● Class: It is a programmer defined data type, which includes local functions as well as
local data. You can think of a class as a template for making many instances of the same
kind (or class) of object.
● Object: An individual instance of the data structure defined by a class. You define a class
once and then make many objects that belong to it. Objects are also known as instance.
● Inheritance: When a class is defined by inheriting existing function of a parent class
then it is called inheritance. Here child class will inherit all or few member functions and
variables of a parent class.
● Polymorphism: This is an object oriented concept where the same function can be used
for different purposes. simply, a function name will remain the same but it makes a
different number of arguments and can do different tasks.
● Overloading: Overloading is a type of polymorphism in which some or all of operators
have different implementations depending on the types of their arguments. Similarly,
functions can also be overloaded with different implementation.
● Data Abstraction: Any representation of data in which the implementation details are
hidden (abstracted). Encapsulation refers to a concept where we encapsulate all the data
and member functions together to form an object.
● Constructor: It refers to a special type of function which will be called automatically
whenever there is an object formation from a class.
● Destructor: It refers to a special type of function which will be called automatically
whenever an object is deleted or goes out of scope.
7.1 Class, Objects, Constructor, Destructor:
Class
Classes are the blueprints of objects. One of the big differences between functions and classes is
that a class contains both data (variables) and functions that form a package called an: ‘object’.
Class is a programmer-defined data type, which includes local methods and local variables. Class
is a collection of objects. Object has properties and behavior.
Object:
The fundamental idea behind an object-oriented language is to enclose a bundle of variables and
functions into a single unit and keep both variables and functions safe from outside interference
and misuse. Such a unit is called an object which acts on data.
The mechanism that binds together data and functions are called encapsulation. This feature
makes it easy to reuse code in various projects. The functions declared in an object provides the
way to access the data. The functions of an object are called methods and all the methods of an
object have access to variables called properties.
Creating classes and objects (Instantiation):
The class definition starts with the keyword class followed by a class name, then followed by a
set of curly braces ({}) which enclose constants, variables (called "properties"), and functions
(called "methods") belonging to the class.
· A valid class name (excluding the reserved words) starts with a letter or
underscore, followed by any number of letters, numbers, or underscores.
· Class names usually begin with an uppercase letter to distinguish them from other
identifiers.
· An instance is an object that has been created from an existing class.
· Creating an object from an existing class is called instantiating the object.
· To create an object out of a class, the new keyword must be used.
· Classes should be defined prior to instantiation.
Syntax:
<?php
class Myclass
{
// Add property statements here
// Add the methods here
}
?>
In the following example keyword new is used to instantiate an object. Here $myobj represents
an object of the class Myclass.
<?php
$myobj = new MyClass;
?>
The contents of the class Myclass using var_dump() function display structured information
(type and value) about one or more variables:
<?php
class Myclass
{
// Add property statements here
// Add the methods here
}
$myobj = new MyClass;
var_dump($myobj);
?>
Output:
object(Myclass)#1 (0) { }
Setting Properties
Class member variables are called properties. Sometimes they are referred as attributes or fields.
The properties hold specific data and related with the class in which it has been defined.
Declaring a property in a class is an easy task, use one of the keyword public, protected, or
private followed by a normal variable declaration.
● public: The property can be accessed from outside the class, either by the script or from
another class.
● private: No access is granted from outside the class, either by the script or from another
class.
● protected: No access is granted from outside the class except a class that’s a child of the
class with the protected property or method.
Example:
After an object is instantiated, you can access the property of a class using the object and ->
operator. Any member declared with keyword "private" or "protected" cannot be accessed
outside the method of the class.
Simpleclass.php
<?php
class Myclass
{
public $font_size =10;
}
$f = new MyClass;
echo $f->font_size;
?>
Setting Methods:
The functions which are declared in a class are called methods.
A class method is exactly similar to PHP functions.
❏ Declaring a method in a class is an easy task, use one of the keyword public, protected, or
private followed by a method name.
❏ public : The method can be accessed from outside the class.
❏ private : No access is granted from outside the class.
❏ protected : No access is granted from outside the class except a class that’s a child
of the class with the protected property or method.
❏ A valid method name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores.
❏ The method body enclosed within a pair of braces which contains codes. The opening
curly brace ( { ) indicates the beginning of the method code and the closing curly ( } )
brace indicates the termination of the method.
❏ If the method is not defined by public, protected, or private then default is public.
❏ Can access properties and methods of the current instance using $this (Format
$this->property) for non static property.
Example:
After an object is instantiated, you can access the method of a class using the object and
->(“object operator”) operator. In the following example customize_print() method will print a
string with a specific font size and color within a html paragraph element with the help of php
echo statement.
<?php
class Myclass
{
public $font_size ="18px";
public $font_color = "blue";
public $string_name = "Rajarshi Shahu College (Autonomous), Latur";
public function customize_print()
{
echo "<p
style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_name."</p>";
}
}
$f = new MyClass;
//$f->font_size="50px";
//$f->font_color="red";
//$f->string_name="Programming With PhP";
echo $f->customize_print();
?>
7.2 Access method and properties using $this variable:
During the execution of an object’s method, a special variable called $this is automatically
defined, which denotes a reference to the object itself. By using this variable and the -> notation,
the object’s methods and properties can be further referenced. For example, you can access the
$name property by using $this->name (note that you don’t use a $ before the name of the
property). An object’s methods can be accessed in the same way; for example, from inside one of
person’s methods, you could call getName() by writing $this->getName().
7.3 Public, private, protected properties and methods
Methods can be public, private or protected. Public means that methods can be accessed
everywhere, private means methods can be accessed by the class that defines the member and
protected means methods can be accessed only within the class itself and by inherited and parent
classes.
<?php
// Define a class
class Myclass
{
// Declare a public method
public function my_public_method()
{
echo "This is a Public method";
}
private function my_private_method()
{
echo "This is a Private method";
}
protected function my_protected_method()
{
echo "This is a Protected method";
}
// This is public
function test()
{
$this->my_public_method();
$this->my_private_method();
$this->my_protected_method();
}
}
$obj = new MyClass;
$obj->my_public_method(); //Display This is a Public method
$obj->my_private_method();//Fatal error: Call to private method
Myclass::my_private_method() C:\xampp\htdocs\srss\chap7\ppp.php:28 Stack trace: #0 {main}
thrown in C:\xampp\htdocs\srss\chap7\ppp.php on line 28
$obj>my_protected_method();//Fatal error: Call to undefined function my_protected_method()
in C:\xampp\htdocs\srss\chap7\ppp.php:29 Stack trace: #0 {main} thrown in
C:\xampp\htdocs\srss\chap7\ppp.php on line 29
$obj->test(); //Display This is a Public methodThis is a Private methodThis is a Protected
method
?>
Constructors and Destructors:
When creating a new object, often it’s useful to set up certain aspects of the object at the same time. For example,
you might want to set some properties to initial values, fetch some information from a database to populate the
object, or register the object in some way.
Similarly, when it’s time for an object to disappear, it can be useful to tidy up aspects of the object, such as closing
any related open files and database connections, or unsetting other related objects.
Like most OOP languages, PHP provides you with two special methods to help with these tasks. An object’s
constructor method is called just after the object is created, and its destructor method is called just before the object
is freed from memory.
PHP Constructor methods:
● Constructors allow to initializing object properties ( i.e. the values of properties) when an object is created.
● Classes which have a constructor method execute automatically when an object is created.
● The 'construct' method starts with two underscores (__).
● The constructor is not required if you don't want to pass any property values or perform any actions when
the object is created.
● PHP only ever calls one constructor.
The general syntax for constructor declaration follows:
function __construct([argument1, argument2, ..., argumentN])
{
/* Class initialization code */
}
The type of argument1, argument2,.......,argumentN are mixed.
Construct.php
<?php
// Define a class
class Myclass
{
// Declaring three private varaibles
private $font_size;
private $font_color;
private $string_value;
// Declarte construct method which accepts three parameters
function __construct($font_size,$font_color,$string_value)
{
$this->font_size = $font_size;
$this->font_color = $font_color;
$this->string_value = $string_value;
}
// Declare a method for customize print
function customize_print()
{
echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_value."</p>";
}
}
// Create a new object and passes three parameters
$f = new MyClass('20px','red','Programming with PhP');
// Call the method to display the string
echo $f->customize_print();
?>
Like properties, constructors can call class methods or other functions. In the following example there is no need to
call the method separately (after creating the object and passing the parameters, see the previous example) as it is
already declared within the constructor. See the following example :
<?php
// Define a class
class Myclass
{
// Declaring three private variables
private $font_size;
private $font_color;
private $string_value;
// Declarte construct method which accepts three parameters and the method customize_print()
function __construct($font_size,$font_color,$string_value)
{
$this->font_size = $font_size;
$this->font_color = $font_color;
$this->string_value = $string_value;
$this->customize_print();
}
// Declare a method for customize print
function customize_print()
{
echo "<p style=font-size:".$this->font_size.";color:".$this->font_color.";>".$this->string_value."</p>";
}
}
// Create a new object and passes three parameters
$f = new MyClass('20px','red', 'Programming with PhP');
?>
PHP Destructors methods:
● The destructor is the counterpart of constructor.
● A destructor function is called when the object is destroyed
● A destructor function cleans up any resources allocated to an object after the object is destroyed.
● A destructor function is commonly called in two ways: When a script ends or manually delete an object
with
● the unset() function
● The 'destructor' method starts with two underscores (__).
The general syntax for destructor declaration follows :
function __destruct
{
/* Class initialization code */\
}
The type of argument1, argument2,.......,argumentN are mixed.
Example:
<?php
// Define a class
class MyClass
{
function __construct()
{
echo 'w3resource'.'<br>';
$this->name = "MyClass";
}
function __destruct()
{
echo "Destroying… " . $this->name . "<br>";
}
}
$obj = new MyClass();
?>
7.4 Static properties and method:
Static properties:
Static properties can be called directly - without creating an instance of a class.
Static properties are declared with the static keyword:
Syntax
<?php
class ClassName {
public static $staticProp = "rsml";
}
?>
To access a static property use the class name, double colon (::), and the property name:
Syntax
ClassName::staticProp;
Let's look at an example:
Example
<?php
class pi {
public static $value = 3.14159;
}
// Get static property
echo pi::$value;
?>
Static methods:
Static methods can be called directly - without creating an instance of a class.
Static methods are declared with the static keyword:
Syntax
<?php
class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
To access a static method use the class name, double colon (::), and the method name:
Syntax
ClassName::staticMethod();
Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
// Call static method
greeting::welcome();
?>
7.5 Inheritance & code reusability:
To inherit the properties and methods from another class, use the extends keyword in the class definition, followed
by the name of the base class:
class Person
{
public $name, $address, $age;
}
class Employee extends Person
{
public $position, $salary;
}
The Employee class contains the $position and $salary properties, as well as the $name, $address, and $age
properties inherited from the Person class.
If a derived class has a property or method with the same name as one in its parent class, the property or method in the derived class takes precedence over the property or method in the parent class. Referencing the property returns the value of the property on the child, while referencing the method calls the method on the child.
To access an overridden method on an object’s parent class, use the parent:: method() notation:
parent::birthday(); // call parent class's birthday() method
A common mistake is to hardcode the name of the parent class into calls to overridden methods:
Creature::birthday(); // when Creature is the parent class This is a mistake because it distributes knowledge of the parent class’s name throughout the derived class.
Using parent:: centralizes the knowledge of the parent class in the extends clause.
If a method might be subclassed and you want to ensure that you’re calling it on the current class, use the self::method() notation:
self::birthday(); // call this class's birthday() method
7.6 Polymorphism:
Polymorphism is derived from two Greek words. Poly (meaning many) and morph (meaning forms). Polymorphism is one of the PHP Object Oriented Programming (OOP) features. In general, polymorphism means the ability to have many forms. If we say it in other words, "Polymorphism describes a pattern in Object Oriented Programming in which a class has varying functionality while sharing a common interface.".
There are two types of Polymorphism; they are:
1. Compile time (function overloading)
2. Run time (function overriding)
But PHP "does not support" compile time polymorphism.
Runtime polymorphism
The Runtime polymorphism means that a decision is made at runtime (not compile time) or we can say we can have multiple subtype implements for a super class, function overloading is an example of runtime polymorphism. I will first describe function overloading. When we create a function in a derived class with the same signature (in other words a function has the same name, the same number of arguments and the same type of arguments) as a function in its parent class then it is called method overriding.
Example:
<?php
interface Shape {
public function calcArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius)
{
$this -> radius = $radius;
}
// calcArea calculates the area of circles
public function calcArea()
{
return $this -> radius * $this -> radius * pi();
}
}
class Rectangle implements Shape {
private $width;
private $height;
public function __construct($width, $height)
{
$this -> width = $width;
$this -> height = $height;
}
// calcArea calculates the area of rectangles
public function calcArea()
{
return $this -> width * $this -> height;
}
}
$circ = new Circle(3);
$rect = new Rectangle(3,4);
echo $circ -> calcArea();
echo "</br>";
echo $rect -> calcArea();
?>
7.7 Parent:: & self:: keyword:
PHP supports two reserved class names that make it easier when writing OO applications. self:: refers to the current class and it is usually used to access static members, methods, and constants. parent:: refers to the parent class and it is most often used when wanting to call the parent constructor or methods. It may also be used to access members and constants. You should use parent:: as opposed to the parent’s class name because it makes it easier to change your class hierarchy because you are not hard-coding the parent’s class name.
The following example makes use of both parent:: and self:: for accessing the Child and Ancestor classes:
<?php
class pen {
const NAME = "Cello";
function __construct()
{
echo "In " . self::NAME . " constructor </br>";
}
}
class Child extends pen {
const NAME = "Cello greeper";
function __construct()
{
parent::__construct();
echo "In " . self::NAME . " constructor";
}
}
$obj = new Child();
?>
The previous example outputs
In Ancestor constructor
In Child constructor
Make sure you use these two class names whenever possible.
7.8 Instanceof operator:
The instanceof operator is used in PHP to find out if an object is an instantiated instance of a class.
Syntax:
$a instanceof MyClass
Operands: This operator contains two operands which are listed below:
· $a: This is used as an object.
· MyClass: It is a class name.
Return Value: It returns True if the object is of this class or has this class as one of its parents else it will return a
False value.
<?php
// PHP program to illustrate instanceof
// operator
// sample class
class student{
var $store = 'Hello students!';
}
// create a new object
$stud = new studdents();
// Checks if $stud is an object of class students
if ($stud instanceof students) {
echo "Yes";
}
?>
Output: Yes
7.9 Interface:
Interfaces provide a way for defining contracts to which a class adheres; the interface provides method prototypes and constants, and any class that implements the interface must provide implementations for all methods in the interface. Here’s the syntax for an interface definition:
interface interfacename
{
[ function functionname();
...
]
}
To declare that a class implements an interface, include the implements keyword and any number of interfaces,
separated by commas:
interface Printable
{
function printOutput();
}
class ImageComponent implements Printable
{
function printOutput()
{
echo "Printing an image...";
}
}
An interface may inherit from other interfaces (including multiple interfaces) as long as none of the interfaces it inherits from declare methods with the same name as those declared in the child interface.
No comments:
Post a Comment