In PHP, I wish to import 2 third-party classes, which have the same name. For example:
// in file libs/3rdparty/AppleTree/Apple.php
class Apple extends SomeOtherModel {
// class details
}
// in file libs/3rdparty/AppleSeed/Apple.php
class Apple extends SomeModel {
// class details
}
Given that their constructor is the same, e.g.:
$appletree = new Apple();
$appleseed = new Apple();
How can PHP differentiate the two classes? In Java, we can append the class path before the constructor.
Note: I'm using PHP 5 & I can't modify the classes as they are used by other class files.
it's not the prettiest and it might not be the most efficient but it DOES work. The concept is this, instead of "including" the files, you read them in as strings, wrap the namespace that you give it around it then evaluate it this will then allow you to call each function with a namespace...
I need to add some mad props to algis for his code in This example i tweaked it to do what you wanted to do.
function create_namespace($str, $namespace) {
$php_start = 0;
$tag = '<?php';
$endtag = '?>';
$start_pos = $php_start + strlen($tag);
$end_pos = strpos($str, $endtag, $start_pos);
$php_code = substr($str, $start_pos, $end_pos - $start_pos);
if (strtolower(substr($php_code, 0, 3)) == 'php')
$php_code = substr($php_code, 3);
$part1 = "namespace $namespace ;";
ob_start();
eval($part1 . $php_code);
ob_end_clean();
}
$str1 = file_get_contents('apple1.php');
$str2 = file_get_contents('apple2.php');
create_namespace($str1, "red");
create_namespace($str2, "green");
$apple1=new red\apple();
$apple2=new green\apple();
echo $apple1->color();
echo "<br/>";
echo $apple2->color();
output:
red
green
You can use name spaces, but you cannot simply include the file as bkdude specified (Although the idea is right) You will have to add namespace declarion to the top of those files that delare the classed So something like following
#file1
namespace red{
class Apple
{
function me()
{
echo __CLASS__;
}
}
}
#file2
namespace green {
class Apple
{
function me()
{
echo __CLASS__;
}
}
}
And include those file wherever you are using them, you will then be able to use as follows.
$apple1 = new red\Apple();
$apple2 = new green\Apple();
$apple1->me();
$apple2->me();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With