Page 1 of 1

namespaces seem strange

Posted: Mon Dec 27, 2010 8:16 am
by IconMan7
I have a file with the following code:

Code: Select all

namespace abc;
class widget
{
}
if (class_exists('widget')){echo 'y';} else {echo 'n';}
I get a 'n'.

When I adjust the last line:

Code: Select all

if (class_exists('abc\widget')){echo 'y';} else {echo 'n';}
now I get a 'y'.
This seems strange, since I declared the namespace at the top of the page. So why do I need to repeat it before I check if the class exists? Adding a "use abc" to indicate I'm using that namespace doesn't seem to help.

Thanks!

Re: namespaces seem strange

Posted: Mon Dec 27, 2010 12:00 pm
by rcrd.ortiz
Hi, you could try this

Code: Select all

namespace abc;
class Widget
{
    public función __conxtruct()
    {
        echo get_class( $this );
    }
}
$a = new abc\Widget();
 

Re: namespaces seem strange

Posted: Mon Dec 27, 2010 12:19 pm
by requinix
class_exists(), and many other reflection-based functions, require the full path to the class. They do not take the current namespace into account.

You can

Code: Select all

if (class_exists(__NAMESPACE__ . '\\widget')){echo 'y';} else {echo 'n';}