namespaces seem strange

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
IconMan7
Forum Newbie
Posts: 1
Joined: Mon Dec 27, 2010 8:09 am

namespaces seem strange

Post 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!
rcrd.ortiz
Forum Newbie
Posts: 11
Joined: Sun Dec 26, 2010 10:46 am

Re: namespaces seem strange

Post 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();
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: namespaces seem strange

Post 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';}
Post Reply