note 44806 added to function.eval
| From: | LeighPurdie at osu1 dot php dot net | Date: | Tue, 17 Aug 2004 08:10:29 +0000 |
| Subject: | note 44806 added to function.eval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-74797@lists.php.net to get a copy of this message | ||
This is an absolutely horrible hack, but if you're caught in a situation where you do NOT
control class names, but really need to include files with potentially conflicting classes, then the
following MIGHT help get you started.
Ideally, you would be able to 'uninclude' an included file, but since you cannot...
Assumptions:
* File names and class names are the same (minus '.php')
Setup:
Assume two directories, called 'One' and 'Two', both containing a file
'Goo.php', both of which implement the class "Goo".
Another file
One/
Goo.php:
<?php
Class Goo {
function blah() {
print "This is One/Goo.php\n";
}
}
?>
Two/
Goo.php:
<?php
Class Goo {
function blah() {
print "This is Two/Goo.php\n";
}
}
?>
./
test.php:
The following code (test.php) uses the 'SafeInclude' class (below):
#!/usr/bin/php -q
<?php
include_once("SafeInclude.inc");
$si=new SafeInclude();
$classname=$si->IncludeFile("One/Goo.php");
$goo=new $classname;
$goo->blah();
$classname=$si->IncludeFile("Two/Goo.php");
$goo2=new $classname;
$goo2->blah();
?>
./
SafeInclude.inc:
And here's the SafeInclude.inc file:
<?php
Class SafeInclude
{
var $count=0;
function IncludeFile($file)
{
$this->count++;
$ques="?";
if(!$file) { return(0); }
# In snare, the filename is the same as the class.
$classname=basename($file,".php");
if(class_exists($classname)) {
# Already exists!
$newclassname=$classname . $this->count;
$contents=file($file);
$string="${ques}>";
foreach($contents as $line) {
$line=eregi_replace("^[ \t]+Class[ \t]+" .
$classname," Class $newclassname",$line);
$string .= $line;
}
$string .= "<${ques}php ";
eval($string);
return($classname . $this->count);
} else {
include_once($file);
return($classname);
}
}
}
?>
Output:
$ ./test.php
This is One/Goo.php
This is Two/Goo.php
As I said, this is a horrible hack - use in emergencies only, and under controlled conditions.
Anyone have any other options?
----
Manual Page -- http://www.php.net/manual/en/function.eval.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44806
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44806&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44806&report=yes
Search -- http://master.php.net/manage/user-notes.php