<?php
namespace NotGlobalNamespace;

ini_set('date.timezone', 'UTC');

function inject_code($code) {
	$fileName = tempnam(sys_get_temp_dir(), 'testCase');
	file_put_contents($fileName, $code);
	require $fileName;
	unlink($fileName);
}

$file1 = <<<'EOF1'
<?php namespace F\o\o; 

function bar($marker) {
	echo "$marker => " . date('c') . "\n";
}

EOF1;
inject_code($file1);

echo "These first 6 lines should show the current date stamp:\n";
\F\o\o\bar(1);                   // bar calls date for us, but we need to specify its FQN
echo "2 => " . date('c') . "\n"; // We can, of course call date ourselves, because it's in the global namespace.
// bar(3);                       // Can't do this, because it won't resolve in our namespace.

// so we can do this:

$file2 = <<<'EOF2'
<?php

function bar($m) {
	return \F\o\o\bar($m);
}

EOF2;
inject_code($file2);

// Now we can do this:
\F\o\o\bar(4);
// and this too:
bar(5);

// Now if we want bar to call something else:
$file3 = <<<'EOF3'
<?php namespace F\o\o; 

function date($f) {
	return "*** INTERCEPTED ***";
}

EOF3;
inject_code($file3);

// This won't affect us:
echo "6 => " . date('c') . "\n";


echo "All these remaining lines *SHOULD* show 'intercepted':\n";

// but we can call it directly:
echo "7 => " . \F\o\o\date('c') . "\n";

// But according to the name resolution rules bar should now call our new date
\F\o\o\bar(8);                   // *** EXCEPT THIS DOESN'T WORK ***
// and this too:
bar(9);                          // *** NOR DOES THIS ***

// What about a new function:
$file3 = <<<'EOF3'
<?php namespace F\o\o; 

function baz($marker) {
	echo "$marker => " . date('c') . "\n";
}

EOF3;
inject_code($file3);

\F\o\o\baz(10);                  // But this works...

// or globally...
$file4 = <<<'EOF4'
<?php

function baz($m) {
	return \F\o\o\baz($m);
}

EOF4;
inject_code($file4);

baz(11);                         // ... and even this works, 
bar(12);                         // *** BUT THIS IS STILL BROKEN. ***

// any different from here?
$file5 = <<<'EOF5'
<?php

bar(13);                         // *** STILL BROKEN! ***

EOF5;
inject_code($file5);

echo "WHY is this broken??? (at least for me with PHP 5.6.30)\n";