Forum Moderators: coopster

Message Too Old, No Replies

Problem reusing php include in same calling file

         

stevo555

11:33 pm on Sep 12, 2005 (gmt 0)

10+ Year Member



I am trying to reuse the same php include file (Categories.php) within the same calling file (file1.php). I want to be able to call this file and pass it different variables each time. The code looks like this...

<?php
$MainCat="Seasonal";
echo "$MainCat";
include 'Categories.php';
?>
<?php
$MainCat="Promotion";
echo "$MainCat";
include 'Categories.php';
?>

I am getting the following error:
Fatal error: Cannot redeclare getdirarray() (previously declared in /homepages/33/htdocs/Categories.php:56) in /homepages/33/htdocs/Categories.php on line 56

Obviously it can't declare the array that's in Categories.php more than once. Is there a way to do this? Can I reset some parameter before calling the include again?

I seem to be perfectly able to reuse php file includes inside a .shtml file using the virtual function as below.
<!--#include virtual="Categories.php?MainCat=Seasonal"-->
<!--#include virtual="Categories.php?MainCat=Promotion"-->
<!--#include virtual="Categories.php?MainCat=Club_Type"-->

But I really need to be able pass php variables to it on the fly.

Any help would be appreciated. Thanks!

grandpa

8:32 am on Sep 13, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Hi stevo555. Welcome to WebmasterWorld

For what you are trying to do, I would use a class object. A class is loaded once, and you invoke with a reference. Here's an example.

The class is called basket and is placed in a file I call basket.inc. It's job is to tell me whatever I want to know about contents of a shopping cart. (This example is not complete)
=======================================================
<?php
class basket {
var $items;
var $empty;
function basket()
{
global $cart;
if(isset($cart))
{
$this->items=unserialize(stripslashes($cart));
if ( gettype($this->items) == "array" )
{
$this->empty=false;
}
else
$this->empty=true;
}
else
$this->empty=true;
}

function add_item($artnr, $num) {
echo "<br>$artnr , $num";
$this->items[$artnr] += $num;
return $items;
}
}
?>
=======================================================

To use the class, in my php script I would have this code.

include_once ("basket.inc"); // this returns item data from our tables
$additem = new basket;

Then, when I'm ready to check, I use something like this.
$result = $additem->additem($PROD1, $ROW);

$additem is the reference to the class object. So by using $additem->additem($PROD1, $ROW);, what I am saying is: Invoke the class, use the additem function in the class, and pass the parameters $PROD1 and $ROW. The results will be returned to the variable $result.

All of this is simplified for example only. But it's the direction I would take if trying to solve your problem.

stevo555

2:29 pm on Sep 13, 2005 (gmt 0)

10+ Year Member



Grandpa, thanks for your input. Unfortunately, your example is a bit over my head. I'm fairly new to PHP.

It seems there should be a simple way to call a subroutine (via include) mutiple times from the parent php file and not have the same variables conflict with eachother.

grandpa

2:44 pm on Sep 13, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



There is a way, and it's the class object.

You probably already know about functions in a php script. With a function you can write it one time in the script and reference it whenever you are ready. A class works much the same way. In fact, you could probably write your entire Categories.php as a function. But this sort of thing tend to get unwieldly, and so a class is the better answer.

The authoritative reference for classes is found here [us2.php.net]. If you need help sorting it all out this forum is one of the best places around.

baze22

3:32 pm on Sep 13, 2005 (gmt 0)

10+ Year Member



I'm guessing that you have a function called getdirarray() in Categories.php. The simplest fix would be to pull out the functions from Categories.php and put them in their own inlcude file (maybe functions.php) and then include that prior to including the others like this:
<?php
include 'functions.php';
$MainCat="Seasonal";
echo "$MainCat";
include 'Categories.php';
?>
<?php
$MainCat="Promotion";
echo "$MainCat";
include 'Categories.php';
?>

This way functions are only declared once.
baze

stevo555

3:46 pm on Sep 13, 2005 (gmt 0)

10+ Year Member



OK, so I get the concept of using a class object. It's a collection of functions and variables. But the implementation of it is making my head spin. I'm having a hard time correlating the shopping cart example to what I'm trying to accomplish.

1. Can I just wrap the entire script inside Categories.php inside a class object?
2. If so what would my include statment look like. I'm hazy on what exactly the $additem = new basket; does. I'm gathering that "new backet" is calling a fresh function with new variables and all. But I don't understand what to do with $additem in my situation.

My Categories.php is a script that parses a file directory for images, then loads those images into a simple two column gallery. My goals is to be able to pass this script a variable $MainCat which points it to the directory I want parsed. And be able to call it more than once from the same file. It works perfectly other than I can't call it more than once becuase the array getdirarray() has already been declasred. So now I need to figure out how to use the class object to accomplish this.

Here is the code for Categories.php if that helps clarify. Thanks for your patience with me.


// ROOT DIRECTORY OF IMAGES
$path = "samples/$Product/$MainCat";
$pathicons = "samples/00_secureicons";
// IMAGES PER ROW
$break = "3";
$TotalWidth = "530";
$TotDirCount = 0;
$ColumnWidth = $TotalWidth / $break;
$breakplusone = $break + 1;
$breakplustwo = $break + 2;
$breaktimestwo = $break * 2;
$count_dir = 0;

//Main Function
function GetDirArray($sPath)
{
//Load Directory Into Array
$handle=opendir($sPath);
while ($file = readdir($handle))
$retVal[count($retVal)] = $file;
//Clean up and sort
closedir($handle);
sort($retVal);
return $retVal;
}

echo "<table id=CategoryTable width=100% border=0 cellpadding=0 cellspacing=0>";
echo "<tr>";

// Count Total Directories
$d1 = GetDirArray("$path");
while (list(, $category) = each ($d1)) {
if(is_dir("$path/$category") && $category!="." and $category!=".."):
$TotDirCount++;
endif;
}

// Fetch main directory, loop through looking for subdirectories only
$d1 = GetDirArray("$path");
while (list(, $category) = each ($d1)) {
if(is_dir("$path/$category") && $category!="." and $category!=".."):
// strip category to clean title
$cat_title=str_replace("_", " ", substr($category, 3));
$cat_title2=(substr($category, 3));
// Get specs on preview image
ClearStatCache();
$preview_size = GetImageSize("$path/$category/_Icon.gif");
$preview_width = $preview_size[0];
$preview_height = $preview_size[1];
$dircount++;
// Display Link With Icon
echo "<td>";
echo "<table border=0 cellpadding=0 cellspacing=0>";
echo "<tr><td align=center width=$ColumnWidth><img src='$path/$category/_Icon.gif' border=0 ALT='$fullsize_noext' height=$preview_height width=$preview_width>";
echo "<br><a href='Templates.php?target=/$category/&Product=$Product&MainCat=$MainCat'><B>$cat_title</B></a></td>";
echo "</tr></table></td>\n";
$count_dir++;
if (($count_dir % $break) == 0) {
echo "</tr>\n";
if ($count_dir <> $TotDirCount) {
echo "<tr><td colspan=$breaktimestwo><div class=HorizRuleCatList></div></td></tr>\n";
}
echo "<tr>\n";
}
endif;
}

echo "</table>";
?>

baze22

4:06 pm on Sep 13, 2005 (gmt 0)

10+ Year Member



Looking at your code you could make it a function (and include it functions.php) like this:

function DisplayCategoryTable($path,$category,$MainCat){
echo "<table id=CategoryTable width=100% border=0 cellpadding=0 cellspacing=0>";
echo "<tr>";

// Count Total Directories
$d1 = GetDirArray("$path");
while (list(, $category) = each ($d1)) {
if(is_dir("$path/$category") && $category!="." and $category!=".."):
$TotDirCount++;
endif;
}
// Fetch main directory, loop through looking for subdirectories only
$d1 = GetDirArray("$path");
while (list(, $category) = each ($d1)) {
if(is_dir("$path/$category") && $category!="." and $category!=".."){
// strip category to clean title
$cat_title=str_replace("_", " ", substr($category, 3));
$cat_title2=(substr($category, 3));
// Get specs on preview image
ClearStatCache();
$preview_size = GetImageSize("$path/$category/_Icon.gif");
$preview_width = $preview_size[0];
$preview_height = $preview_size[1];
$dircount++;
// Display Link With Icon
echo "<td>";
echo "<table border=0 cellpadding=0 cellspacing=0>";
echo "<tr><td align=center width=$ColumnWidth><img src='$path/$category/_Icon.gif' border=0 ALT='$fullsize_noext' height=$preview_height width=$preview_width>";
echo "<br><a href='Templates.php?target=/$category/&Product=$Product&MainCat=$MainCat'><B>$cat_title</B></a></td>";
echo "</tr></table></td>\n";
$count_dir++;
if (($count_dir % $break) == 0) {
echo "</tr>\n";
if ($count_dir <> $TotDirCount) {
echo "<tr><td colspan=$breaktimestwo><div class=HorizRuleCatList></div></td></tr>\n";
}
echo "<tr>\n";
}
}
echo "</table>";
}
}

This way your code would be rewritten as:

<?php
include 'functions.php';
DisplayCategoryTable($path,$category,'Seasonal');
DisplayCategoryTable($path,$category,'Promotion');
DisplayCategoryTable($path,$category,'whatever');
?>

I didn't really go over this code, but I did notice that counters weren't initialized in this code, like $TotDirCount. Good idea to initialize variables prior to use.

I might have missed some global variables. If there are any, those would need to be rewritten as $_GLOBAL['varname'].

stevo555

11:53 pm on Sep 13, 2005 (gmt 0)

10+ Year Member



THANK YOU baze22!

Putting the function declaration in the parent file or separate include worked like a charm.