1

I'm trying to learn the namespaces feature in PHP, however how do I access classes that are in namespaces?

Like, say I have the class Users inside the namespace called Core, how do I access that namespace from the Pages namespace?

1 Answer 1

4

I believe this is what you're after:

<?php
$users = new \Core\Users;
echo $users->all();

When you want to use a class that's inside a namespace, you need to define the "absolute path" to the class, like I have done in the example. Note the \ before the Core namespace, that tells PHP to use the Core namespace that is located in the root or "global" namespace of PHP.

So if you wanted to access the Users class in your Pages namespace, you would do the following:

<?php
namespace Pages;

$users = new \Core\Users;
echo $users->all();

There's also another way to use the Users class, which is:

<?php
namespace Pages;
use \Core\Users as Users;

$users = new Users;
echo $users->all();

The use \Core\Users; line allows you to use the Users class from the Core namespace as if it were a normal class inside the Pages namespace.

1
  • Oh I get it now, I was about to give up with the namespaces, totally confused my noob php mind. thank you. Sep 7, 2011 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.