Unit 4
Unit 4
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
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.
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
12 Constructor A special function is automatically called when an object of the same class
is formed.
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;
}
}
echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
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;
?>
Example
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
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:
<?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:
<?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
Output:
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:
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:
Constructors Destructors
7
UNIT 4 CLASS & OBJECTS IN PHP
Constructors Destructors
Multiple constructors can exist in a class. Only one Destructor can exist in a class.
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;
}
}
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.
<?php
class myclass {
public function __set($name, $value) {
echo "setting $name property to $value \n";
$this->$name = $value;
}
9
UNIT 4 CLASS & OBJECTS IN PHP
$obj->myproperty="Hello World!";
output –
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);
}
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) {
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.
<?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
}
}
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.
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 −
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 −
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.
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.
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 −
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