From my below code, I try to call the sayHi method, in class Cat with namespace foo;
but it not work, I have to use "use" to change name to call it;
<?php
namespace foo;
class Cat
{
public static function sayHi()
{
echo "Meow";
}
}
namespace bar;
class Cat
{
public static function sayHi()
{
echo "Hello";
}
}
foo\Cat::sayHi(); //try to use backslash path but Fatal error: Class 'bar\foo\Cat' not found
?>
if I use Cat::sayHi();
it always call the method from namespace bar that I don't want. so Question: Are there any method that solve this problem without use 'use
' alias?
When you declare a namespace, your code operates within that namespace until you declare another, or until the end of the file. You're doing this:
namespace foo;
class Cat {}
namespace bar;
class Cat {}
// here you are in namespace bar
foo\Cat::sayHi();
Since you're already in the bar namespace, and your namespace reference doesn't anchor the root namespace, this final line is interpreted as:
\bar\foo\Cat::sayHi();
Simply anchor to the root:
\foo\Cat::sayHi();
Or put your call to foo\Cat::sayHi();
in another file.