You are on page 1of 46

UNIT-IV WT

Why use classes and


objects?
PHP is a primarily procedural language
small programs are easily written without
adding any classes or objects
larger programs, however, become
unordered with so many disorganized
functions
grouping related data and behavior into
objects helps manage size and
complexity

Object Oriented Concept


Classes, which are the "blueprints" for an
object and are the actual code that defines
the properties and methods.
Objects, which are running instances of a
class and contain all the internal data and
state information needed for your
application to function.
Encapsulation, which is the capability of an
object to protect access to its internal data
Inheritance, which is the ability to define a
class of one kind as being a sub-type of a
different kind of class (much the same way a
square is a kind of rectangle).

Creating Class
Let's start with a simple example.
Save the following in a fi
le called class.php
<?php
class Demo
{
}
?>

Constructing and using


objects

# construct an object
$name = new ClassName(parameters);
# access an object's field (if the field is
public)
$name->fieldName
# call an object's method

$name->methodName(parameters);

PHP

Adding Method
The Demo class isn't particularly
useful if it isn't able to do anything,
so let's look at how you can create a
method.
<?php
class Demo
{
function SayHello($name)
{
echo Hello $name !;
}
}
?>

Adding Properties
Adding a property to your class is as
easy as adding a method.
<?php
class Demo
{
public $name;
function SayHello()
{
echo Hello $this->$name !;
}
}
?>

Object Instantiation
You can instantiate an object of type
Demo like this:
<?php
require_once('class.php');
$objDemo = new Demo();
$objDemo->name = mbstechinfo;
$objDemo->SayHallo();
?>

Example on Class

Creating Objects in PHP


Once you defined your class, then
you can create as many objects:
$physics = new Books;
$maths = new Books;
$chemistry = new Books;

Calling Member
Functions

Protecting Access to Member


Variables
There are three different levels of
visibility that a member variable or
method can have :
Public
members are accessible to any and all code

Private
members are only accessible to the class itself

Protected
members are available to the class itself, and to
Public classes
is the default
visibility
levelitfor any member variables
that inherit
from
or functions that do not explicitly set one, but it is good
practice to always explicitly state the visibility of all the
members of the class.

Class Constants
It is possible to define constant values
on a per-class basis remaining the same
and unchangeable.
Constants differ from normal variables in
that you don't use the $ symbol to
declare or use them
The value must be a constant
expression, not (for example) a variable,
a property, a result of a mathematical
operation, or a function call

<?php

classMyClass
{
constconstant='constantvalue';
functionshowConstant()
{
echoself::constant."\n";
}
}
echoMyClass::constant."\n";

?>

Static Keyword
Declaring class properties or
methods as static makes them
accessible without needing an
instantiation of the class.
A property declared as static can not
be accessed with an instantiated
class object

Contructor
Constructor is the method that will
be implemented when object has
been initiated
Commonly, constructor is used to
initialize the object
Use function __construct to create
<?php
constructor
in PHP
class
Demo
{
function __construct
{
}
}

Constructor Functions:
Constructor Functions are special
type of functions which are called
automatically whenever an object is
created.
PHP provides a special function called
__construct() to define a
constructor. You can pass as many as
arguments you like into the
constructor function.

Following example will create one


constructor for Books class and it
will initialize price and title for the
book at the time of object creation.

Now we don't need to call set function separately to


set price and title. We can initialize these two
member variables at the time of object creation only.

Destructor
Destructor, is method that will be run
when object is ended
<?php
class Demo
{
function __destruct
{
}
}
?>

Inheritance
There are many benefits of
inheritance with PHP, the most
common is simplifying and reducing
instances of redundant code

PHP class definitions can optionally inherit


from a parent class definition by using the
extends clause. The syntax is as follows:

The effect of inheritance is that the child


class (or subclass or derived class) has
the following characteristics:
Automatically has all the member
variable declarations of the parent class.
Automatically has all the same member
functions as the parent, which (by
default) will work the same way as those
functions do in the parent.

example inherit Books class and adds more


functionality based on the requirement.

Interfaces:
Interfaces are defined to provide a common
function names to the implementors.
Syntax:

Syntax: Interface implementation

Abstract Classes:
An abstract class is one that cannot be
instantiated, only inherited. You declare an
abstract class with the keyword abstract,
like this:

Note : function definitions inside an


abstract class must also be preceded by
the keyword abstract.

Abstract classes and


interfaces

interface InterfaceName {
public function name(parameters);
public function name(parameters);
...
}
class ClassName implements InterfaceName { ...

PHP

abstract class ClassName {


abstract public function name(parameters);
...

PHP

Abstract classes and


interfaces
interfaces are supertypes that specify
method headers without implementations
cannot be instantiated; cannot contain function
bodies or fields
enables polymorphism between subtypes
without sharing implementation code

abstract classes are like interfaces, but you


can specify fields, constructors, methods
also cannot be instantiated; enables
polymorphism with sharing of implementation
code

Final
If the class itself is being defined final
then it cannot be extended.

PHP File Handling


PHP Filesystem Introduction
The filesystem functions allow you to access and
manipulate the filesystem.
Opening a File
The fopen() function is used to open files in PHP.

The first parameter of this function contains the


name of the file to be opened
the second parameter specifies in which mode the
file should be opened:
If the fopen() function is unable to open the
specified file, it returns 0 (false).

<html>
<body>
<?php
$handle=fopen("welcome.txt","r") ;
if($handle)
{
echo File opened ok.;
}
?>
</body>
</html>

Closing a File
The fclose() function is used to close
an open file:
Check End-of-file
The feof() function checks if the
"end-of-file" (EOF) has been reached.
Cannot read from files opened in w,
a, and x mode!

Reading a File Line by Line


The fgets() function is used to read a single
line from a file.
After a call to this function the file pointer
has moved to the next line.
Example:
<?php
$file = fopen("welcome.txt", "r") or
exit("Unable to open file!");
//Output a line of the file until the end is
reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>

Reading a File Character by Character


The fgetc() function is used to read a
single character from a file.
After a call to this function the file
pointer moves to the next character.
Example:
<?php
$file=fopen("welcome.txt","r");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

The newline characters from the file were


simply sent to the browser, which doesnt
display newline characters
To convert them to <br> elements instead
Example
<?php
$file=fopen("welcome.txt","r") or exit("Unable
to open file!");
while ($ch=fgetc($file))
{
if($ch==\n){
$ch=<br>;
}
echo $ch;
}
fclose($file);
?>

Reading a whole file at once


Use file_get_contents function.
Syntax:
file_get_contents(file name (or) file
path);
Example
<?php
$text=file_get_contents(
http://www.php.net);
$ft=str_replace(\n,<br>,$text);
echo $ft;
?>

Reading a file into an Array


Use file function.
Syntax:
file(file name (or) file path);
Example
<?php
$text=file(file.txt);
foreach($text as $number=>$line)
{
echo Line $number: , $line, <br>;
}
?>

Checking if a File Exists


Use file_exists function.
Syntax:
file_exists(file name );
Example
<?php
$fname=abc.txt;
If(file_exists($fname)){
$text=file($fname);
foreach($text as $number=>$line)
{
echo Line $number: , $line, <br>;
}
}
?>

Getting File Size


Use filesize function.
Syntax:
filesize(file name );
Example
<?php
echo The file abc.txt is ,
filesize(abc.txt), bytes long.;
?>

Opening a file with readfile( ) in PHP

<?PHP
$file_contents =
readfile("dictionary.txt");
print $file_contents;
?>

Count lines in a file


<?php
$file = "somefile.txt";
$lines = count(file($file));
echo "There are $lines lines in $file";
?>

You might also like