0% found this document useful (0 votes)
2 views16 pages

Unit 4

Uploaded by

suhasguddemane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

Unit 4

Uploaded by

suhasguddemane
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIT 4 CLASS & OBJECTS IN PHP

Class &Objects in PHP:


We first need to understand the concept of object-oriented programming, also known as
OOPs, before learning about PHP classes

Object-Oriented Programming / OOPs


It is a form of programming concept where everything is considered on an object, and then
we implement software with the help of using these different objects.
S.N Terminology Definition
o

1 Class The user-defined data type combines variables, local data, and functions.

2 Objects These are local instances created by the developer to access the content of
the class

3 Member These are none other than variables defined inside a class and are only
Variable accessed by member functions

4 Member These are none other than functions defined inside a class and are
Function generally used to access data objects

5 Inheritance It is one of the main properties of object-oriented programming, where


traits and properties of a superior class are given to a subclass. The
subclass inherits member function and variables present in the parent class

6 Parent class The main class generally inherits some of its traits and properties to its
child class or other class. These types of classes are also known as
superclasses or base classes.

7 Child class A subclass inherits some of its traits and properties from its parent class or
another class, these types of classes are also known as subclasses or
derived classes.

8 Polymorphism It is one of the base concepts of object-oriented programming, which


states that a single function can be used for various other reasons. In this,
the name of the function remains the same, but arguments can be different

9 Overloading It is a type of polymorphism where a single function class is overloaded


with different forms of implementation depending on certain types of
arguments, or we can overload the same type of function using different
implementations.

10 Data It is a specific type of data where the data implementation details are
abstraction hidden.

11 Encapsulation Process in which all data and member functions are wrapped together to

1
UNIT 4 CLASS & OBJECTS IN PHP

create a new object.

12 Constructor A special function is automatically called when an object of the same class
is formed.

13 Destructor A special function is automatically called when an object goes out of


scope or gets deleted.

Define a Class in php


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!

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

2
UNIT 4 CLASS & OBJECTS IN PHP

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

PHP - The $this Keyword


The $this keyword refers to the current object, and is only available inside methods.

Look at the following example:

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

So, where can we 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;

3
UNIT 4 CLASS & OBJECTS IN PHP

}
}
$apple = new Fruit();
$apple->set_name("Apple");

echo $apple->name;
?>

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

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

echo $apple->name;
?>

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 (__)!

Constructors are the very basic building blocks that define the future object and its nature.
You can say that the Constructors are the blueprints for object creation providing values for
member functions and member variables.
Once the object is initialized, the constructor is automatically called. Destructors are for
destroying objects and automatically called at the end of execution.

Syntax:
__construct():

function __construct()
{
// initialize the object and its properties by assigning
//values
}

4
UNIT 4 CLASS & OBJECTS IN PHP

Constructor types:

 Default Constructor:It has no parameters, but the values to the default


constructor can be passed dynamically.
 Parameterized Constructor: It takes the parameters, and also you can pass
different values to the data members.
 Copy Constructor: It accepts the address of the other objects as a parameter.

Pre-defined Default Constructor: By using function __construct(), you can define a


constructor.
Note: In the case of Pre-defined Constructor(__construct) and user-defined constructor in
the same class, the Pre-defined Constructor becomes Constructor while user-defined
constructor becomes the normal method.

<?PHP
class Tree
{
function Tree()
{
echo "Its a User-defined Constructor of the class Tree";
}
function __construct()
{
echo "Its a Pre-defined Constructor of the class Tree";
}
}
$obj= new Tree();
?>

Output:

Its a Pre-defined Constructor of the class Tree

Parameterized Constructor: The constructor of the class accepts arguments or


parameters.
The -> operator is used to set value for the variables. In the constructor method, you can
assign values to the variables during object creation.

<?php
class Employee
{
Public $name;
Public $position;
function __construct($name,$position)
{
// This is initializing the class properties
$this->name=$name;
$this->position=$position;
}
function show_details()
{

5
UNIT 4 CLASS & OBJECTS IN PHP

echo $this->name." : ";


echo "Your position is ".$this->profile."\n";
}
}
$employee_obj= new Employee("Rakesh","developer");
$employee_obj->show_details();
$employee2= new Employee("Vikas","Manager");
$employee2->show_details();
?>

Output:

Rakesh : Your position is developer


Vikas : Your position is Manager
Advantages of using Constructors:

 Constructors provides the ability to pass parameters which are helpful in


automatic initialization of the member variables during creation time.
 The Constructors can have as many parameters as required and they can be
defined with the default arguments.
 They encourage re-usability avoiding re-initializing whenever instance of the
class is created .
 You can start session in constructor method so that you don’t have to start in all
the functions everytime.
 They can call class member methods and functions.
 They can call other Constructors even from Parent class.

Destructor: Destructor is also a special member function which is exactly the reverse of
constructor method and is called when an instance of the class is deleted from the memory.
Destructors (__destruct ( void): void) are methods which are called when there is no
reference to any object of the class or goes out of scope or about to release explicitly.
They don’t have any types or return value. It is just called before de-allocating memory for
an object or during the finish of execution of PHP scripts or as soon as the execution
control leaves the block.
Global objects are destroyed when the full script or code terminates. Cleaning up of
resources before memory release or closing of files takes place in the destructor method,
whenever they are no longer needed in the code. The automatic destruction of class objects
is handled by PHP Garbage Collector.

<?php
class SomeClass
{
function __construct()
{
echo "In constructor, ";
$this->name = "Class object! ";
}
function __destruct()
{
echo "destroying " . $this->name . "\n";

6
UNIT 4 CLASS & OBJECTS IN PHP

}
}
$obj = new Someclass();
?>
Output:

In constructor, destroying Class object!

Note: The destructor method is called when the PHP code is executed completely by its last
line by using PHP exit() or die() functions.

Note: In the case of inheritance, and if both the child and parent Class have destructors
then, the destructor of the derived class is called first, and then the destructor of the parent
class.

Advantages of destructors:

 Destructors give chance to objects to free up memory allocation , so that enough


space is available for new objects or free up resources for other tasks.
 It effectively makes programs run more efficiently and are very useful as they
carry out clean up tasks.
 Comparison between __constructors and __destructors:

Constructors Destructors

Accepts one or more arguments. No arguments are passed. Its void.

function name is _construct(). function name is _destruct()

It has same name as the class with prefix


It has same name as the class.
~tilda.

Constructor is involved automatically Destructor is involved automatically when


when the object is created. the object is destroyed.

Used to de-initialize objects already


Used to initialize the instance of a class. existing to free up memory for new
accommodation.

Used to make the object perform some task


Used to initialize data members of class.
before it is destroyed.

Constructors can be overloaded. Destructors cannot be overloaded.

It is called each time a class is instantiated It is called automatically at the time of

7
UNIT 4 CLASS & OBJECTS IN PHP

Constructors Destructors

or object is created. object deletion .

Allocates memory. It deallocates memory.

Multiple constructors can exist in a class. Only one Destructor can exist in a class.

If there is a derived class inheriting from


The destructor of the derived class is called
base class and the object of the derived
and then the destructor of base class just the
class is created,
reverse order of
the constructor of base class is created and
constructor.
then the constructor of the derived class.

The concept of copy constructor is allowed


where an object is initialized from the
No such concept is allowed.
address of another object .

PHP - Access Modifiers


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

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");

8
UNIT 4 CLASS & OBJECTS IN PHP

echo $apple->get_name();
?>

Overloading in PHP
What is function overloading? Function overloading is the ability to create multiple
functions of the same name with different implementations.
Function overloading contains same function name and that function performs different
task according to number of arguments
Property and Rules of overloading in PHP:
 All overloading methods must be defined as Public.
 After creating the object for a class, we can access a set of entities that are properties or
methods not defined within the scope of the class.
 Such entities are said to be overloaded properties or methods, and the process is called
as overloading.
 For working with these overloaded properties or functions, PHP magic methods are
used.
 Most of the magic methods will be triggered in object context except __callStatic()
method which is used in a static context.

Types of Overloading in PHP: There are two types of overloading in PHP.


 Property Overloading
 Method Overloading

Property Overloading: PHP property overloading is used to create dynamic properties in


the object context.
Before performing the operations, we should define appropriate magic methods. which are,
 __set(): triggered while initializing overloaded properties.
 __get(): triggered while using overloaded properties with PHP print statements.
 __isset(): This magic method is invoked when we check overloaded properties with
isset() function
 __unset(): Similarly, this function will be invoked on using PHP unset() for
overloaded properties.

<?php
class myclass {
public function __set($name, $value) {
echo "setting $name property to $value \n";
$this->$name = $value;
}

public function __get($name) {


echo "value of $name property is ";
return $this->$name;
}
}
$obj = new myclass();
# This calls __set() method

9
UNIT 4 CLASS & OBJECTS IN PHP

$obj->myproperty="Hello World!";

# This call __get() method


echo "Retrieving myproperty: " . $obj->myproperty . PHP_EOL;
?>

output –

setting myproperty property to Hello World!

Retrieving myproperty: Hello World!

The __set() and __get() magical methods also set and retrieve a property which is declared as
private. Add the following statement inside myclass (before the function definitions)

private $myproperty;
You can check if the property, define __isset() method in myclass −
public function __isset($name) {
return isset($this->$name);
}

Check if the property is set with this statement −

var_dump (isset($obj->myproperty));
Which in this case returns true.
To unset the dynamically created property with the __unset() method defined in myclass −
public function __unset($name) {
unset($this->$name);
}
The following code would return false −
var_dump (isset($obj->myproperty));

Method Overloading
Two magic methods used to set methods dynamically are __call() and __callStatic().
public __call (string $name , array $arguments) : mixed
public static __callStatic (string $name , array $arguments) : mixed

The __call() is triggered when invoking inaccessible (not defined or private) methods in an object
context. On the other hand, the __callStatic() is triggered when invoking inaccessible methods in
a static context.

Example
The following example demonstrates method overloading in PHP

Open Compiler

<?php

10
UNIT 4 CLASS & OBJECTS IN PHP

class myclass {
public function __call($name, $args) {

// Value of $name is case sensitive.


echo "Calling object method $name with " . implode(" ", $args). "\n";
}
public static function __callStatic($name, $args) {
echo "Calling static method $name with " . implode(" ", $args). "\n";
}
}
$obj = new myclass();

# This invokes __call() magic method


$obj->mymethod("Hello World!");

# This invokes __callStatic() method


myclass::mymethod("Hello World!");
?>
It will produce the following output −
Calling object method mymethod with Hello World!
Calling static method mymethod with Hello World!
Note that the use of "->" operator implies that the method is an instance method, and "::"
operator means that the method is a static method.

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}.";

11
UNIT 4 CLASS & OBJECTS IN PHP

}
}

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

Example Explained
The Strawberry class is inherited from the Fruit class.

This means that the Strawberry class can use the public $name and $color properties as well as
the public __construct() and intro() methods from the Fruit class because of inheritance.

The Strawberry class also has its own method: message().

PHP - Form Handling


HTML Form is a collection various form controls such as text fields, checkboxes, radio buttons,
etc., with which the user can interact, enter or choose certain data that may be either locally
processed by JavaScript (client-side processing), or sent to a remote server for processing with
the help of server-side programming scripts such as PHP.

One or more form control elements are put inside <form> and </form> tags. The form element is
characterized by different attributes such as name, action, and method.
<form [attributes]>
Form controls
</form>
Form Attributes

Out of the many attributes of the HTML form element, the following attributes are often required
and defined −

Action Attribute
a string representing the URL that processes the form submission. For
example, http://example.com/test.php. To submit the for-data to the same PHP script in which
the HTML form is defined, use the PHP_SELF server variable −
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">

Enctype Attribute

12
UNIT 4 CLASS & OBJECTS IN PHP

specifies the method using which the form-data should be encoded before sending it to the server.
Possible values are −

 application/x-www-form-urlencoded − The default value.


 multipart/form-data − Use this if the form contains <input> elements with type=file.
 text/plain − Useful for debugging purposes.

Method Attribute
a string representing the HTTP method to submit the form with. The following methods are the
possible values of method attribute −

 post − The POST method; form data sent as the request body.
 get (default) − The GET; form data appended to the action URL with a "?" separator.
Use this method when the form has no side effects.
 dialog − When the form is inside a <dialog>, closes the dialog and causes a submit event
to be fired on submission, without submitting data or clearing the form.

Name Attribute
The name of the form. The value must not be the empty string, and must be unique if there are
multiple forms in the same HTML document.

Target Attribute
a string that indicates where to display the response after submitting the form. Should be one of
the following −

 _self (default) − Load into the same browsing context as the current one.
 _blank − Load into a new unnamed browsing context.
 _parent − Load into the parent browsing context of the current one.
 _top − Load into the top-level browsing context (an ancestor of the current one and has
no parent).

Hence, a typical HTML form, used in a PHP web application looks like −

<form name="form1" action="<?php echo $_SERVER['PHP_SELF'];?>" action="POST">


Form controls
</form>
Form Elements

A HTML form is designed with different types of controls or elements. The user can interact with
these controls to enter data or choose from the available options presented. Some of the elements
are described below −

Input Element
The input element represents a data field, which enables the user to enter and/or edit the data.

13
UNIT 4 CLASS & OBJECTS IN PHP

The type attribute of INPUT element controls the data. The INPUT element may be of the
following types −

Text
A text field to enter a single line text.

<input type="text" name="employee">


Password
A single line text filed that masks the entered characters.

<input type="password" name="pwd"><br>


Checkbox
A rectangular checkable box which is a set of zero or more values from a predefined list.

<input type="checkbox" id="s1" name="sport1" value="Cricket">


<label for="s1">I like Cricket</label><br>
<input type="checkbox" id="s2" name="sport2" value="Football">
<label for="s2">I like Football</label><br>
<input type="checkbox" id="s3" name="sport3" value="Tennis">
<label for="s3">I like Tennis</label><br><br>
Radio
This type renders a round clickable button with two states (ON or OFF), usually a part of multiple
buttons in a radio group.

<input type="radio" id="g1" name="gender" value="Male">


<label for="g1">Male</label><br>
<input type="radio" id="g2" name="female" value="Female">
<label for="g2">Female</label><br>
File
The input type renders a button captioned file and allows the user to select a file from the client
filesystem, usually to be uploaded on the server. The form’s enctype attribute must be set to
"multipart/form-data"

<input type="file" name="file">


Email
A single line text field, customized to accept a string conforming to valid email ID.

14
UNIT 4 CLASS & OBJECTS IN PHP

URL
A single line text filed customized to accept a string conforming to valid URL.

Submit
This input element renders a button, which when clicked, initiates the the submission of form data
to the URL specified in the action attribute of the current form.

<input type="submit" name="Submit">

Select Element
The select element represents a control for selecting amongst a set of options. Each choice is
defined with option attribute of Select Control. For example −

<select name="Subjects" id="subject">


<option value="Physics">Physics</option>
<option value="Chemistry">Chemistry</option>
<option value="Maths">Maths</option>
<option value="English">English</option>
</select>
Form Example

Let us use these form elements to design a HTML form and send it to a PHP_SELF script

<html>
<body>
<form method = "post" action = "<?php
echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Name:</td>
<td><input type = "text" name = "name"></td>
</tr>
<tr>
<td>E-mail: </td>
<td><input type = "email" name = "email"></td>
</tr>
<?php
$name = $email =””;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
}
echo "<h2>Your given values are as:</h2>";

15
UNIT 4 CLASS & OBJECTS IN PHP

echo $name;
echo "<br>";

echo $email;
echo "<br>";
?>
</body>
</html>

16

You might also like