it is not the most beautiful and may not be the most effective, but it works. The concept is that instead of “including” the files, you read them as strings, wrap the namespace that you give it, and then evaluate it, and this allows you to call each function with the namespace ...
I need to add crazy details to algis for my code in 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
source share