Sunday, March 29, 2009

Require and Include parameter in Php

Suppose you have two php files named class1.php and class2.php and now from class1.php file you need to access the class class2 which is defined under class2.php.

With both include and require command you can include the class2.php and then uses the classes, objects, variables defined under class2.php.

Both "include" and "require" commands are almost identical except about how they handle failures. Both of them generates warning (E_WARNING) upon failure. But "require" results fatal error (E_ERROR) upon missing file and thus halt processing of the page. In contrast, "include" does processing rest of the lines of the file after issuing warning.

So if you want to process rest of the lines of the file after missing file then use include. If you want to halt processing rest of the lines of the file then use require.

Following is an example.

My class2.php file contents,

<?php
$test1="Momin";
$test2="Arju";
class Class2{
function display(){
echo "This is include/require test";
}
}
?>

And my class1.php file contents,

<?php
require 'Class2.php';
echo "It is in Class1: Variable from class2 $test1 $test2";
echo "<br />";
$class1Instance=new Class2();
$class1Instance->display();
?>

Now in browser class1.php displays,
It is in Class1: Variable from class2 Momin Arju
This is include/require test

Let's now change the class1.php file as below:

<?php
require 'Classnotfound.php';
echo "It is in Class1: Variable from class2 $test1 $test2";
echo "<br />";
$class1Instance=new Class2();
$class1Instance->display();
?>

Now on broswer running class2.php fails with message,
Warning: require(Classnotfound.php) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\class1.php on line 2

Fatal error: require() [function.require]: Failed opening required 'Classnotfound.php' (include_path='.;C:\xampp\php\pear\') in C:\xampp\htdocs\class1.php on line 2

Replacing require by include and see the differences.

<?php
include 'Classnotfound.php';
echo "It is in Class1: Variable from class2 $test1 $test2";
echo "<br />";
$class1Instance=new Class2();
$class1Instance->display();
?>

Warning: include(Classnotfound.php) [function.include]: failed to open stream: No such file or directory in C:\xampp\htdocs\class1.php on line 2

Warning: include() [function.include]: Failed opening 'Classnotfound.php' for inclusion (include_path='.;C:\xampp\php\pear\') in C:\xampp\htdocs\class1.php on line 2
It is in Class1: Variable from class2

Fatal error: Class 'Class2' not found in C:\xampp\htdocs\class1.php on line 5

Note that include display echos under class1.php but require does not.
Related Documents
http://arjudba.blogspot.com/2009/03/class-inheritance-example-in-php.html

http://arjudba.blogspot.com/2009/03/class-concepts-and-usage-syntax-in-php.html

No comments:

Post a Comment