0% found this document useful (0 votes)
17 views

PHP UNIT-2 Notes

The document explains PHP access modifiers (public, private, protected) and their usage in class methods and variables, emphasizing encapsulation as a means to protect data. It also contrasts cookies and sessions, detailing their characteristics and how to manage them in PHP. Additionally, it provides examples of setting, checking, accessing, and deleting cookies in PHP.

Uploaded by

preeti
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

PHP UNIT-2 Notes

The document explains PHP access modifiers (public, private, protected) and their usage in class methods and variables, emphasizing encapsulation as a means to protect data. It also contrasts cookies and sessions, detailing their characteristics and how to manage them in PHP. Additionally, it provides examples of setting, checking, accessing, and deleting cookies in PHP.

Uploaded by

preeti
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

PHP Access Modifiers

To set the access rights for class methods and variables we use access modifiers which are nothing but
PHP keywords. We can even assign some of these access modifiers to the class itself to make the class
behave in a special way.

Following are the PHP keywords which are used as access modifiers along with their meaning:

1. public: When we define class members as public, then they are accessible from anywhere, even
from outside of the class scope.

2. private: When we define class members as private, they can only be accessed from within the
class itself.

3. protected: This is same as private, with one exception, the class members defined as protected
can still be accessed from its subclass(We will learn about subclasses when we will learn
about Inheritance).

 Public: Public properties can be accessed by any code, whether that code is
inside or outside the class. If a property is declared public, its value can be
read or changed from anywhere in your script.
 <?php
 class parent
 {
 public $x = 100 ; # public attributes
 public $y = 50 ;
 function add()
 {
 echo $a = $this->x + $this->y ;
 echo " ";
 }
 }
 class child extends parent
 {
 function sub()
 {
 echo $s = $this->x - $this->y ;
 }

 }

 $obj = new child;

 // It will return the addition result
 $obj->add() ;

 // It's a derived class of the main class,
 // which has a public object and therefore can be
 // accessed, returning the subtracted result.
 $obj->sub() ;

 ?>
 Private: Private properties of a class can be accessed only by code inside
the class. So if we create a property that’s declared private, only methods
and objects inside the same class can access its contents.
 <?php
 class parent
 {
 private $a = 75 ; # private attributes
 private $b = 5 ;
 private function div() # private member function
 {
 echo $d = $this->a / $this->b ;
 echo " ";
 }
 }
 class child extends parent
 {
 function mul()
 {
 echo $m = $this->a * $this->b ;
 }

 }

 $obj= new child;

 // It's supposed to return the division result
 // but since the data and function are private
 // they can't be accessed by a derived class
 // which will lead to fatal error .
 $obj->div();

 // It's a derived class of the main class,
 // which's accessing the private data
 // which again will lead to fatal error .
 $obj->mul();
 ?>
 Protected: Protected class properties are a bit like private properties in that
they can’t be accessed by code outside the class, but there’s one little
difference in any class that inherits from the class i.e. base class can also
access the properties.
 <?php
 class parent
 {
 protected $x = 1000 ; # protected attributes
 protected $y = 100 ;
 function div()
 {
 echo $d = $this->x / $this->y ;
 echo " ";
 }
 }
 class child extends parent
 {
 function sub()
 {
 echo $s = $this->x - $this->y ;
 }

 }
 class derived # Outside Class
 {
 function mul()
 {
 echo $m = $this->x * $this->y ;
 }

 }
 $obj= new child;

 // It will return the division result
 $obj->div();

 // Since it's a derived class of the main class,
 $obj->sub();

 // Since it's an outside class, therefore it
 // will produce a fatal error .
 $obj->mul();

 ?>
Encapsulation
The wrapping up of data and methods into a single unit (called class) is known as encapsulation.
Encapsulation is a protection mechanism for the data members and methods present inside the class. In
the encapsulation technique, we are restricting the data members from access to outside world end-
user.

In PHP, encapsulation utilized to make the code more secure and robust. Using encapsulation, we are
hiding the real implementation of data from the user and also does not allow anyone to manipulate data
members except by calling the desired operation.

Example

Let' understand this through an example.

<?php

class ATM {

private $custid;

private $atmpin;

public function PinChange($custid,$atmpin) {

---------perform tasks-----

public function CheckBalance($custid,$atmpin){

---------perform tasks-----

public function miniStatement($custid) {

---------perform tasks-----

$obj = new ATM();

$obj ->CheckBalance(10005285637,1**3);

?>

Explanation:
In this example, all the ATM class data members (variable) are marked with the private modifier. It
implies that we can not directly access ATM class data members (property). So, we can't change the
class property directly. The only approach to change the class property (data members) is calling a
method (function). That’s the reason we have stated all the ATM class methods with a public access
modifier. The user can pass the expected arguments to a class method to perform a particular task.

Suppose anyone wants to check balance then he needs to access the CheckBalance() method with the
required arguments custid="10005285637"and

atmpin="1**3". This is called Data hiding through Encapsulation.

Difference Between Session and Cookies :

Cookie Session

Cookies are client-side files on a local


Sessions are server-side files that contain user data.
computer that hold user information.

Cookies end on the lifetime set by the When the user quits the browser or logs out of the
user. programmed, the session is over.

It can only store a certain amount of


It can hold an indefinite quantity of data.
info.

We can keep as much data as we like within a session,


The browser’s cookies have a maximum
however there is a maximum memory restriction of 128
capacity of 4 KB.
MB that a script may consume at one time.

Because cookies are kept on the local


To begin the session, we must use the session start()
computer, we don’t need to run a
method.
function to start them.

Cookies are not secured. Session are more secured compare than cookies.

Cookies stored data in text file. Session save data in encrypted form.
Cookies stored on a limited data. Session stored a unlimited data.

In PHP, to get the data from Cookies , In PHP , to get the data from Session, $_SESSION the
$_COOKIES the global variable is used global variable is used

In PHP, to destroy or remove the data stored within a


We can set an expiration date to delete
session, we can use the session_destroy() function, and
the cookie’s data. It will automatically
to unset a specific variable, we can use the unset()
delete the data at that specific time.
function.

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.
<!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>
Checking Whether a Cookie Is Set Or Not: It is always advisable to check
whether a cookie is set or not before accessing its value. Therefore to check
whether a cookie is set or not, the PHP isset() function is used. To check
whether a cookie “Auction_Item” is set or not, the isset() function is executed as
follows:
Example: This example describes checking whether the cookie is set or not.
 PHP

<!DOCTYPE html>

<?php

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

?>

<html>
<body>

<?php

if (isset($_COOKIE["Auction_Item"]))

echo "Auction Item is a " . $_COOKIE["Auction_Item"];

else

echo "No items for auction.";

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

Output:
Checking for the cookie to be set

Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE
superglobal variable is used. It is an associative array that contains a record of
all the cookies values sent by the browser in the current request. The records
are stored as a list where the cookie name is used as the key. To access a
cookie named “Auction_Item”, the following code can be executed.
Example: This example describes accessing & modifying the cookie value.
 PHP

<!DOCTYPE html>

<?php

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

?>

<html>

<body>

<?php

echo "Auction Item is a " . $_COOKIE["Auction_Item"];

?>

<p>
<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

Output:

Accessing the Cookie value

Deleting Cookies: The setcookie() function can be used to delete a cookie. For
deleting a cookie, the setcookie() function is called by passing the cookie name
and other arguments or empty strings but however this time, the expiration date
is required to be set in the past. To delete a cookie named “Auction_Item”, the
following code can be executed.
Example: This example describes the deletion of the cookie value.
 PHP

<!DOCTYPE html>

<?php

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


?>

<html>

<body>

<?php

setcookie("Auction_Item", "", time() - 60);

?>

<?php

echo "cookie is deleted"

?>

<p>

<strong>Note:</strong>

You might have to reload the page

to see the value of the cookie.

</p>

</body>

</html>

Output:
Deleting the Cookie

Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie() function:

Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

You might also like