Professional Documents
Culture Documents
Unit 4
Unit 4
CHAPTER I
In all programming and scripting language, a function is a block of statements that can be used
repeatedly in a program. In PHP, the concept of the function is the same as in other language like
'C'.
There are more than 1,000 in-built functions into the standard PHP distribution. Besides these we can
define functions as per our requirements. These are called 'User Defined Function'.
SYNTAX:
Function function-name ()
{
statement 1 :
statement 2 :
statement 3 :
......
}
Elements of function
Function: A function declaration starts with the special word 'function'.
Name of the function: The function name is defined by the user.A valid function name starts with a
letter or underscore, followed by any number of letters, numbers, or under scores.Remember that
function names are case-insensitive.
Opening and Closing curly braces ({ } ): The function body enclosed within a pair of braces which
may contain variable names and actual function code. The opening curly brace ( { ) indicates the
beginning of the function code and the closing curly ( } ) brace indicates the termination of the
function.
Example:
<?php
function myfunction()
{
echo "Good Morning";
Department of Computer Science Page 1
}
myfunction();
?>
Example:Functionswith in a function
<?php
function function1()
{
function function2()
{
echo "Good Morning <br>";
}
}
function1();
function2();
?>
PHP Function arguments, Returning Values
PHP Function arguments
In PHP information are passed to functions through argument list, which is a comma-
delimited list of expression.
There are three different ways of passing arguments to a function, arguments by value (the
default), passing by reference, and default argument values.
PHP Function arguments by values
The argument can be any valid expression. The expression is evaluated and its value assigned
to the appropriate variable in the function. In the following function $a assigned the value 10
and $b assigned the value 20:
EXAMPLE:
Functionadd($a, $b)
{
...
}
add(10, 20);
<?php
class phpClass{
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
[..]
}
[..]
}
?>
<?php
class Books{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP
Once you defined your class, then you can create as many objects as you like of that class type.
Following is an example of how to create object using new operator.
Here we have created three objects and these objects are independent of each other and they
will have their existence separately.
Next we will see how to access member function and process member variables.
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example:
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Constructor Functions:
Constructor Functions are special type of functions which are called automatically whenever an
object is created.
So we take full advantage of this behavior, by initializing many things through constructor functions.
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. Check following example below:
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Destructor:
Like a constructor function you can define a destructor function using function __destruct ().
You can release all the resources with-in a destructor.
Inheritance:
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 have all the member variable declarations of the parent class.
Automatically has all the same a member function as the parent, which (by default) will work the
same way as those functions do in the parent.
Following examples inherit Books class and adds more functionality based on the requirement.
Now apart from inherited functions, class Novel keeps two additional member functions.
Function Overriding:
Function definitions in child classes override definitions with the same name in parent classes.
In a child class, we can modify the definition of a function inherited from parent class.
In the following example getPrice and getTitle functions are overridden to return some values.
function getPrice(){
Public Members:
Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be
accessed in three possible situations:
From outside the class in which it is declared
From within the class in which it is declared
From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the members
of a class then you define class members as private or protected.
Private members:
By designating a member private, you limit its accessibility to the class in which it is declared.
The private member cannot be referred to from classes that inherit the class in which it is declared
and cannot be accessed from outside the class.
A class member can be made private by using private keyword in front of the member.
class MyClass {
private $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
private function myPrivateFunction() {
class MyClass {
protected $car = "skoda";
$driver = "SRK";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
protected function myPrivateFunction() {
return("I'm visible in child class!");
}
}
Interfaces:
Interfaces are defined to provide a common function names to the implementers.
Different implementers can implement those interfaces according to their requirements. You can say,
interfaces are skeltons which are implemented by developers.As of PHP5, it is possible to define an
interface, like this:
Constants:
A constant is somewhat like a variable, in that it holds a value, but is really more like a function
because a constant is immutable.
Once you declare a constant, it does not change.Declaring one constant is easy, as is done in this
version of MyClass:
class MyClass {
constrequiredMargin = 1.7;
function __construct($incomingValue) {
// Statements here run every time
// an instance of the class
// is created.
}
}
Note that function definitions inside an abstract class must also be preceded by the keyword abstract.
It is not legal to have abstract function definitions inside a non-abstract class.
Department of Computer Science Page 12
Static Keyword:
Declaring class members or methods as static makes them accessible without needing an
instantiation of the class.
A member declared as static can not be accessed with an instantiated class object (though a static
method can).Try out following example:
<?php
class Foo
{
public static $my_static = 'foo';
Final Keyword:
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by
prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method Base Class::more Testing()
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called<br>";
}
class Name
{
var $_firstName;
var $_lastName;
function Name($first_name, $last_name)
{
$this->_firstName = $first_name;
$this->_lastName = $last_name;
}
function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name
{
var $_middleInitial;
function NameSub1($first_name, $middle_initial, $last_name) {
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}
function toString() {
return(Name::toString() . " " . $this->_middleInitial);
}
}
CHAPTER II
Example:
<?php
//readfile intostring
$str= file_get_contents('example.txt') ordie('ERROR:Cannotfind
file');
echo$str;
?>
An alternative method of reading data from a file is PHP’s file()function, which accepts the
name and path to a file and reads the entire file into an array, with each element of the array
representing one line of the file.
To process the file, all you need do is iterate over the array using a foreachloop.
Example:
<?php
//readfile intoarray
$arr= file('example.txt') ordie('ERROR:Cannotfind
file');
foreach($arras$line) {
echo$line;
}
?>
Example:
WRITING FILES
The flip side of reading data from files is writing data to them. And PHP comes with a couple of
different ways to do this as well.
The first is the file_put_contents() function, a close cousin of the
file_get_contents()function you read about in the preceding section: this function accepts a
filename and path, together with the data to be written to the file,
Example:
Department of Computer Science Page 16
<?php
//writestringtofile
$data= "A fish \noutof\n water\n";
file_put_contents('output.txt', $data)or die('ERROR:Cannotwritefile');
echo'Datawritten tofile';
?>
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite() function.
This function requires two arguments specifying a file pointer and the string of data that is to be
written. Optionally a third integer argument can be included to specify the length of the data to write.
If the third argument is included, writing would will stop after the specified length has been reached.
The following example creates a new text file then writes a short text heading in site it. After
closingthisfileitsexistenceisconfirmedusingfile_exist()functionwhichtakesfilenameas an argument
Example:
<?php
$filename = "/home/user/guest/newfile.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{
echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This isa simple test\n" );
fclose( $file );
?>
<html>
<head>
<title>Writing a file using PHP</title>
</head>
<body>
<?php
if(file_exist( $filename ) )
{
$filesize = filesize( $filename );
$msg = "File created with name $filename ";
Department of Computer Science Page 17
$msg .= "containing $filesize bytes";
echo ($msg );
}
else
{
echo ("File $filename does not exit" );
}
?>
</body>
</html>
PROCESSING DIRECTORIES
PHP also allows developers to work with directories on the file system, iterating through directory
contents or moving forward and backward through directory trees.
Iterating through a directory is a simple matter of calling PHP’s Directory Iterator object,
EXAMPLE
Example:
<?php
//checkfile
if(file_exists('somefile.txt')){
$str= file_get_contents('somefile.txt');
} else{
echo 'Namedfiledoesnotexist. ';
}
//checkdirectory
if(file_exists('somedir')){
$files= scandir('somedir');
<?php
//getfile pathinfoasarray
if(file_exists('example.txt'))
{
print_r(pathinfo('example.txt'));
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>
Retrieving File Attributes
You can obtain detailed information on a particular file, including its ownership, permissions,
and modification and access times, with PHP’s stat()function, which returns this
information as an associative array. Here’s an example:
<?php
//getfile information
if(file_exists('example.txt'))
{
print_r(stat('example.txt'));
} else
{
echo 'Namedfiledoesnotexist. ';
}
?>
You can check if a file is readable, writable or executable with the is readable (), is
writable (), and is executable () functions. The following example illustrates their
usage:
<?php
//getfile information
//output:'File is: readablewritable'
The is_dir()function returns true if the argument passed to it is a directory, while the
is_file()function returns true if the argument passed to it is a file. Here’s an example:
<?php
//testiffileordirectory
if(file_exists('example.txt'))
{
if(is_file('example.txt'))
{
echo'It\'safile.';
}
if(is_dir('example.txt')){
Department of Computer Science Page 22
echo'It\'sadirectory.';
}
} else
{
echo 'ERROR: File doesnotexist.';
}
?>
Creating Directories
To create a new, empty directory, call the mkdir()function with the path and name of the directory
to be created:
Example:
<?php
if(!file_exists('mydir'))
{
if(mkdir('mydir'))
{
echo'Directory successfully created.';
} else
{
echo 'ERROR: Directory couldnotbecreated.';
}
} else
{
echo 'ERROR: Directoryalreadyexists.';
}
?>
Copying Files
You can copy a file from one location to another by calling PHP’s copy()function with the file’s
source and destination paths as arguments. Here’s an example:
<?php
//copyfile
if(file_exists('example.txt')){
if(copy('example.txt', 'example.new.txt')){
echo'File successfullycopied.';
Department of Computer Science Page 23
} else
{
echo 'ERROR: File couldnotbecopied.';
}
} else{
echo 'ERROR: File doesnotexist.';
}
?>
It’s important to note that if the destination file already exists, the copy()function will overwrite it.
UNIT IV
2 MARKS