phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


Reuse Code: Introduction ( Part 1 )

Tag: Reuse Code   Category:
post: 12 Nov 2007 read: 523


Than write new codes, it is more better we reuse existing code. This is one goal of software engineers. This is not because they are very lazy people. Reusing existing code will reduces cost, increases reliability, and improves consistency.

This series tutorial will explains how reusing code leads to more consistent, reliable, maintainable code, with less efort.

PHP provides two very simple statements to allow you to reuse any type of code. Yeah.. require() and include() statement. With these statement, you can load a file into your PHP script. The file can contain anything you would normally type in a script includeing PHP statements, text, HTML tags, PHP Functions, or PHP Classes.

Include()

(All sample below I rewrite from PHP manual) Basic include example():

"vars.php" file:


<?php 
$color = 'green'; 
$fruit = 'apple'; 
?>

"test.php" file:


<?php 

echo "A $color $fruit"; // A 
include 'vars.php'; 
echo "A $color $fruit"; // A green apple 

?>

Require()


<?php 
require 'prepend.php'; 
require $somefile; 
require ('somefile.txt'); 
?>

require() and include() are identical in every way except how they handle failure. include() produces a Warning while require() results in a Fatal Error. In other words, don't hesitate to use require() if you want a missing file to halt processing of the page. include() does not behave this way, the script will continue regardless. Be sure to have an appropriate include_path setting as well.



Series this article:
Reuse Code: Introduction ( Part 1 )
Reuse Code: Using Function in PHP (Part 2)

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting