KEMBAR78
Unit 3 (Part 2) Inheritance | PDF | Class (Computer Programming) | Http Cookie
0% found this document useful (0 votes)
6 views21 pages

Unit 3 (Part 2) Inheritance

The document discusses inheritance in PHP, outlining its types: single, multilevel, and hierarchical inheritance, while noting that multiple inheritance is not supported. It emphasizes the importance of inheritance for code reusability, extensibility, and data hiding. Additionally, the document covers PHP interfaces, sessions, cookies, and the differences between GET and POST methods in PHP.

Uploaded by

tatiboh192
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)
6 views21 pages

Unit 3 (Part 2) Inheritance

The document discusses inheritance in PHP, outlining its types: single, multilevel, and hierarchical inheritance, while noting that multiple inheritance is not supported. It emphasizes the importance of inheritance for code reusability, extensibility, and data hiding. Additionally, the document covers PHP interfaces, sessions, cookies, and the differences between GET and POST methods in PHP.

Uploaded by

tatiboh192
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/ 21

UNIT 3

Inheritance in PHP

Inheritance Type Support in PHP

Single Inheritance YES

Multilevel Inheritance YES

Hierarchical Inheritance YES

Multiple Inheritance NO

Inheritance is a way of extending the existing class functionality in the newly created class. We
can also add functionality to the newly created class apart from extending the base class
functionalities. When we inherit one class, we say an inherited class is a child class (sub-class),
which is called the parent class from which we inherit it. The parent class is also known as the
base class. This is the way that enables better management of the programming code and code
reusability. The idea behind using inheritance is all about better management of the code and the
code reusability. In this topic, we are going to learn about Inheritance in PHP.

Types of Inheritance in PHP

1. Single Inheritance

PHP supports Single inheritance. Single inheritance is a concept in PHP in which only one class
can be inherited by a single class. We need to have two classes in between this process. One is
the base (parent) class, and the other is the child class. Let’s understand the same with an
example. It is popularly known as simple inheritance. This type of inheritance in PHP
language remains the same as JAVA, C++, etc.

Code:

<?php
class MyAccess {
var $var = "This is first var";
protected $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class child extends MyAccess {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo $this->fist_name;
}
}
$obj1 = new child();
$obj1->setVal("Jai Shre");
$obj1->getVal();
?>

MyAccess is the parent, and the child is the name of the child’s class.

2. Multilevel Inheritance
PHP supports Multilevel Inheritance. In this type of inheritance, we will have more than 2
classes. In this type of inheritance, a parent class will be inherited by a child class then that child
class will be inherited by the child class. This type of inheritance in PHP language remains the
same as in C++ etc.
Code:

<?php
class ParentClass {
var $var = "This is first var";
public $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class child_1 extends ParentClass {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo "Extended By Parent Class -". $this->fist_name;
}
}
class child_2 extends child_1 {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo "Extended By child 1 - ".$this->fist_name;
}
}
$obj1 = new child_1();
$obj1->setVal("This is first inherited class");
$obj1->getVal();
echo "<br/><br/>";
$obj2 = new child_2();
$obj2->setVal("This is second inherited class");
$obj2->getVal();

?>

3. Hierarchical Inheritance
PHP supports Hierarchical inheritance. Hierarchical inheritance is the type of inheritance in
which a program consists of a single parent and more than one child class. Let’s understand the
same with this example. This type of inheritance in PHP language remains the same as JAVA,
C++, etc.

Code:

<?php
class ParentClass {
var $var = "This is first var";
public $fist_name;
// simple class method
function returnVar() {
echo $this->fist_name;
}
function set_fist_name($set_this){
$this->fist_name = $set_this;
}
}
class child_1 extends ParentClass {
function setVal($set_this){
$this->fist_name = $set_this;
}
function getVal(){
echo $this->fist_name;
}
}
class child_2 extends ParentClass {
function setVal($set_this){
$this->fist_name = $set_this." - ".$set_this;;
}
function getVal(){
echo $this->fist_name;
}
}
$obj1 = new child_1();
$obj1->setVal("This is first child class");
$obj1->getVal();
echo "<br/><br/>";
$obj2 = new child_2();
$obj2->setVal("This is second child class");
$obj2->getVal();
?>

Importance of Inheritance in PHP


The importance of inheritance is many more as it has huge advantages.

 Code reusability is one of the most frequently used in inheritance; the base class
remains as it is in between the process. As we can see in the above example of all the
inheritance, the code is being re-used from one class to another. We need not be required
to rewrite the same thing again and again.
 A base class can be used by a number of its derived classes in the class hierarchy. Yes,
this is a type of inheritance in which we can extend in parent class with multiple
inheritances.
 Extensibility is one of the advantages of inheritance in which we can extend the base
class feature without making little or no changes to fulfill the business requirements.
Suppose we just go with a parent class with no child class. But in case of need, we can
add the child class to fulfill our business needs later.
 Overriding is another advantage of this inheritance feature in which we can rewrite the
definition of the base class function into the derived class to make changes as per the
business requirements.
 Less amount of code – meantime, we will have less code comparatively while moving
ahead with the inheritance as compared to the traditional way of coding.
 Inheritance also enabled the data hiding features as well. We can expose the only
required part of the parent class to the child class using various PHP Access Modifiers.
 Fully support MVC – we can go for MVC by using the concept of inheritance.

Interface
An Interface allows the users to create programs, specifying the public methods that a class
must implement, without involving the complexities and details of how the particular methods
are implemented. It is generally referred to as the next level of abstraction. It resembles the
abstract methods, resembling the abstract classes. An Interface is defined just like a class is
defined but with the class keyword replaced by the interface keyword and just the function
prototypes. The interface contains no data variables. The interface is helpful in a way that it
ensures to maintain a sort of metadata for all the methods a programmer wishes to work on.
Creating an Interface
Following is an example of how to define an interface using the interface keyword.

<?php

interface MyInterfaceName {

public function methodA();

public function methodB();

?>
Few characteristics of an Interface are:
 An interface consists of methods that have no implementations, which means the
interface methods are abstract methods.
 All the methods in interfaces must have public visibility scope.
 Interfaces are different from classes as the class can inherit from one class only whereas
the class can implement one or more interfaces.
To implement an interface, use the implements operator as follows:

<?php

class MyClassName implements MyInterfaceName{

public function methodA() {

// method A implementation

public function methodB(){

// method B implementation

?>
Concrete Class: The class which implements an interface is called the Concrete Class. It must
implement all the methods defined in an interface. Interfaces of the same name can’t be
implemented because of ambiguity error. Just like any class, an interface can be extended
using the extends operator as follows:

<?php

interface MyInterfaceName1{

public function methodA();

interface MyInterfaceName2 extends MyInterfaceName1{

public function methodB();

?>

Example:
<?php

interface MyInterfaceName{

public function method1();

public function method2();

class MyClassName implements MyInterfaceName{

public function method1(){

echo "Method1 Called" . "\n";

public function method2(){

echo "Method2 Called". "\n";


}

$obj = new MyClassName;

$obj->method1();

$obj->method2();

?>

Output:
Method1 Called
Method2 Called

Advantages of PHP Interface


 An interface allows unrelated classes to implement the same set of methods, regardless of
their positions in the class inheritance hierarchy.
 An interface can model multiple inheritances because a class can implement more than
one interface whereas it can extend only one class.
 The implementation of an inheritance will save the caller from full implementation of
object methods and focus on just he objects interface, therefore, the caller interface
remains unaffected.

What is a session?
In general, session refers to a frame of communication between two medium. A PHP session
is used to store data on a server rather than the computer of the user. Session identifiers or
SID is a unique number which is used to identify every user in a session based environment.
The SID is used to link the user with his information on the server like posts, emails etc.
How are sessions better than cookies?
Although cookies are also used for storing user related data, they have serious security issues
because cookies are stored on the user’s computer and thus they are open to attackers to easily
modify the content of the cookie. Addition of harmful data by the attackers in the cookie may
result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies send the user data each
time the user views a page. Every time the browser requests a URL to the server, all the
cookie data for that website is automatically sent to the server within the request.
Below are different steps involved in PHP sessions:
 Starting a PHP Session: The first step is to start up a session. After a session is started,
session variables can be created to store information. The PHP session_start() function is
used to begin a new session.It also creates a new session ID for the user.
Below is the PHP code to start a new session:

<?php

session_start();

?>

 Storing Session Data: Session data in key-value pairs using


the $_SESSION[] superglobal array.The stored data can be accessed during lifetime of a
session.
Below is the PHP code to store a session with two session variables Rollnumber and
Name:

<?php

session_start();
$_SESSION["Rollnumber"] = "11";

$_SESSION["Name"] = "Ajay";

?>

 Accessing Session Data: Data stored in sessions can be easily accessed by firstly
calling session_start() and then by passing the corresponding key to
the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber and Name
is shown below:

<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';

echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';

?>

Output:
The Name of the student is :Ajay
The Roll number of the student is :11
 Destroying Certain Session Data: To delete only a certain session data,the unset feature
can be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative
session array:

<?php

session_start();

if(isset($_SESSION["Name"])){

unset($_SESSION["Rollnumber"]);

?>

 Destroying Complete Session: The session_destroy() function is used to completely


destroy a session. The session_destroy() function does not require any argument.

<?php

session_start();
session_destroy();

?>

Important Points
1. The session IDs are randomly generated by the PHP engine .
2. The session data is stored on the server therefore it doesn’t have to be sent with every
browser request.
3. The session_start() function needs to be called at the beginning of the page, before any
output is generated by the script in the browser.

PHP Cookies
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the
client computer. They are typically used to keep track of information such as a username that
the site can retrieve to personalize the page when the user visits the website next time. A
cookie can only be read from the domain that it has been issued from. Cookies are usually set
in an HTTP header but JavaScript can also set a cookie directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The
setcookie() function needs to be called prior to any output generated by the script otherwise
the cookie will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general which are:
 Name: It is used to set the name of the cookie.
 Value: It is used to set the value of the cookie.
 Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t
be accessed.
 Path: It is used to specify the path on the server for which the cookie will be available.
 Domain: It is used to specify the domain for which the cookie is available.
 Security: It is used to indicate that the cookie should be sent only if a secure HTTPS
connection exists.
Below are some operations that can be performed on Cookies in PHP:
 Creating Cookies: Creating a cookie named Auction_Item and assigning the value
Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60
seconds).
Example: This example describes the creation of the cookie in PHP.

 PHP
<!DOCTYPE html>

<?php

setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);

?>

<html>

<body>

<?php

echo "cookie is created."

?>

<p>

<strong>Note:</strong>

You might have to reload the

page to see the value of the cookie.

</p>

</body>

</html>
What is the Difference Between GET and POST Methods in PHP?
Parameter GET POST
Data is included
in the request
Data is appended to the URL and visible in the
Visibility body and not
browser's address bar.
visible in the
URL.
No inherent limit
Limited by the URL length, which can vary by on data size,
Data Length browser and server. Typically, around 2048 allowing for large
characters. amounts of data
to be sent.
More secure for
transmitting
Less secure due to visibility in the URL. Sensitive data
sensitive data
Security can be easily exposed in browser history, server logs,
since it's not
etc.
exposed in the
URL.
Suited for
transactions that
result in a change
Ideal for simple data retrieval where the data can be on the server,
Use Case
bookmarked or shared. such as updating
data, submitting
forms, and
uploading files.
Non-idempotent,
meaning multiple
Idempotent, meaning multiple identical requests have identical requests,
Idempotency
the same effect as a single request. may have
different
outcomes.
Not cached by
default since it
Caching Can be cached by the browser and proxies.
can change the
server state.
Data Type Only ASCII characters are allowed. Non-ASCII Can handle
characters must be encoded. binary data in
addition to text,
making it suitable
for file uploads.
Reloading a page
can cause the
browser to
Back/Forward Reloading a page requested by GET does not usually
prompt the user
Buttons require browser confirmation.
for confirmation
to resubmit the
POST request.
Cannot be
bookmarked or
Bookmarks and Easily bookmarked and shared since the data is part shared through
Sharing of the URL. the URL since the
data is in the
request body.
Often causes a
change in server
Generally used for retrieving data without any side
Impact on Server state (e.g.,
effects on the server.
database updates)
or side effects.

Get and Post Methods in PHP


PHP provides two methods through which a client (browser) can send information to the server.
These methods are given below, and discussed in detail:

1. GET method
2. POST method

Get and Post methods are the HTTP request methods used inside the <form> tag to send form
data to the server.

HTTP protocol enables the communication between the client and the server where a browser
can be the client, and an application running on a computer system that hosts your website can be
the server.

GET method

The GET method is used to submit the HTML form data. This data is collected by the
predefined $_GET variable for processing.
The information sent from an HTML form using the GET method is visible to everyone in the
browser's address bar, which means that all the variable names and their values will be displayed
in the URL. Therefore, the get method is not secured to send sensitive information.

For Example

1. localhost/gettest.php?username=Harry&bloodgroup=AB+
The bold part in the above URL is the variables name and italic part contains the values for their
corresponding variable.

With the help of an example, let's understand how the GET method works-

Example

The below code will display an HTML form containing two input fields and a submit button. In
this HTML form, we used the method = "get" to submit the form data.

file: test1.html

1. <html>
2. <body>
3.
4. <form action = "gettest.php" method = "GET">
5. Username: <input type = "text" name = "username" /> <br>
6. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
7. <input type = "submit" />
8. </form>
9.
10. </body>
11. </html>

Create gettest.php file, which will accept the data sent by HTML form.

file: gettest.php
1. <html>
2. <body>
3.
4. Welcome <?php echo $_GET["username"]; ?> </br>
5. Your blood group is: <?php echo $_GET["bloodgroup"]; ?>
6.
7. </body>
8. </html>
When the user will click on Submit button after filling the form, the URL sent to the server
could look something like this:

localhost/gettest.php?username=Harry&bloodgroup=AB-

The output will look like the below output:

Welcome Harry
Your blood group is: AB-

Advantages of GET method (method = "get")

o You can bookmark the page with the specific query string because the data sent by the
GET method is displayed in URL.
o GET requests can be cached.
o GET requests are always remained in the browser history.

Disadvantages of GET Method

o The GET method should not be used while sending any sensitive information.
o A limited amount of data can be sent using method = "get". This limit should not exceed
2048 characters.
o For security reasons, never use the GET method to send highly sensitive information like
username and password, because it shows them in the URL.
o The GET method cannot be used to send binary data (such as images or word documents)
to the server.

POST method

Similar to the GET method, the POST method is also used to submit the HTML form data. But
the data submitted by this method is collected by the predefined superglobal
variable $_POST instead of $_GET.
Unlike the GET method, it does not have a limit on the amount of information to be sent. The
information sent from an HTML form using the POST method is not visible to anyone.

For Example

1. localhost/posttest.php

With the help of an example, let's understand how the POST method works-

Example

The below code will display an HTML form containing two input fields and a submit
button. In this HTML form, we used the method = "post" to submit the form data.

file: test2.html

1. <html>
2. <body>
3.
4. <form action = "posttest.php" method = "post">
5. Username: <input type = "text" name = "username" /> <br>
6. Blood Group: <input type = "text" name = "bloodgroup" /> <br>
7. <input type = "submit" />
8. </form>
9.
10. </body>
11. </html>

Now create posttest.php file to accept the data sent by HTML form.

file: posttest.php

1. <html>
2. <body>
3.
4. Welcome <?php echo $_POST["username"]; ?> </br>
5. Your blood group is: <?php echo $_POST["bloodgroup"]; ?>
6.
7. </body>
8. </html>
When the user will click on Submit button after filling the form, the URL sent to the server
could look something like this:

localhost/posttest.php

The output will look like the below output:

Welcome Harry
Your blood group is: O+

Advantages of POST method (method = "post")

o The POST method is useful for sending any sensitive information because the
information sent using the POST method is not visible to anyone.
o There is no limitation on size of data to be sent using the POST Method. You can send a
large amount of information using this method.
o Binary and ASCII data can also be sent using the POST method.
o Data security depends on the HTTP protocol because the information sent using the
POST method goes through the HTTP header. By using secure HTTP, you can ensure
that your data is safe.

Disadvantages of POST Method

o POST requests do not cache.


o POST requests never remain in the browser history.
o It is not possible to bookmark the page because the variables are not displayed in URL.

$_REQUEST variable

The $_REQUEST variable is a superglobal variable, which can hold the content of both
$_GET and $_POST variable. In other words, the PHP $_REQUEST variable is used to collect
the form data sent by either GET or POST methods. It can also collect the data for $_COOKIE
variable because it is not a method-specific variable.

You might also like