See that accepted answer is already provided. However, hereby a code you can use to take advantage of relative namespaces (note: feel free to use code below for free and reference to author in your code is not required, no guarantees are provided by author and use of code is on own risk).
update: code can be used inside your class to dynamically and quickly load other classes via relative namespaces. Starter of this topic is looking for a way to extend class to other class via relative namespace, that remains not possible also not with this code.
In your class just add the following code:
public function TestRelativeNamespace()
{
// (e.g., param1 = site\lib\firm\package\foo, param2 = .\..\..\different)
$namespace = $this->GetFullNamespace(__NAMESPACE__, '.\\..\\..\\different');
// will print namespace: site\lib\firm\different
print $namespace;
// to create object
$className = $namespace . '\\TestClass';
$test = new $className();
}
public function GetFullNamespace($currentNamespace, $relativeNamespace)
{
// correct relative namespace
$relativeNamespace = preg_replace('#/#Di', '\\', $relativeNamespace);
// create namespace parts
$namespaceParts = explode('\\', $currentNamespace);
// create parts for relative namespace
$relativeParts = explode('\\', $relativeNamespace);
$part;
for($i=0; $i<count($relativeParts); $i++) {
$part = $relativeParts[$i];
// check if just a dot
if($part == '.') {
// just a dot - do nothing
continue;
}
// check if two dots
elseif($part == '..') {
// two dots - remove namespace part at end of the list
if(count($namespaceParts) > 0) {
// remove part at end of list
unset($namespaceParts[count($namespaceParts)-1]);
// update array-indexes
$namespaceParts = array_values($namespaceParts);
}
}
else {
// add namespace part
$namespaceParts[] = $part;
}
}
if(count($namespaceParts) > 0) {
return implode('\\', $namespaceParts);
}
else {
return '';
}
}
Foo\Baris a totally different namespace thanFoo\Bar\Baz.Foo\Barnamespace and callnew Baz\Bat()it will be in theFoo\Bar\Baz\Bat()namespace. However if you callnew \Baz\Bat()it will be in theBaz\Bat()namespace.