Reputation: 13
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?
Upvotes: 1
Views: 332
Reputation: 1088
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.
Upvotes: 4