Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import 2 Class with same name

Tags:

php

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.

like image 708
Raptor Avatar asked Oct 04 '22 04:10

Raptor


2 Answers

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
like image 52
bkdude Avatar answered Oct 18 '22 11:10

bkdude


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();
like image 32
xelber Avatar answered Oct 18 '22 11:10

xelber