Since in the previous section you learned how to link two sample classes named “User” to distinct namespaces, it’s time to see how to use their instances within the same PHP script, without getting any errors from the PHP engine. That being explained, please take a look at the following code sample, which demonstrates how to display information about a couple of fictional users by utilizing the two namespaces declared earlier. Here it is: // include class files require_once 'bloguser.php'; require_once 'cmsuser.php'; try{ // create new instance of 'User' class (belongs to UserManagement::CMS namespace) $cmsUser=new UserManager::CMS::User('Alejandro','Gervasio','alejandro@domain.com'); // display user data echo 'First Name: '.$cmsUser->getFirstName().'<br />'; echo 'Last Name: '.$cmsUser->getLastName().'<br />'; echo 'Email: '.$cmsUser->getEmail().'<br />';
/* displays the following First Name: Alejandro Last Name: Gervasio Email: alejandro@domain.com */ // create new instance of 'User' class (belongs to UserManagement::Blog namespace) $blogUser=new UserManager::Blog::User('John','Doe','john@domain.com'); // display user data echo 'First Name: '.$blogUser->getFirstName().'<br />'; echo 'Last Name: '.$blogUser->getLastName().'<br />'; echo 'Email: '.$blogUser->getEmail().'<br />'; /* displays the following First Name: John Last Name: Doe Email: john@domain.com */ } catch(Exception $e){ echo $e->getMessage(); exit(); } As you can see from the earlier example, I first created a pair of users for each “User” class, and then displayed some basic data about them on screen. Logically, the most interesting aspect to note here is how each of these classes are instantiated by means of their corresponding namespaces. Even when there are actually two classes named “User,” they belong to distinct namespaces. Pretty good, right? And with this last example, I have finished this humble introduction to linking two sample classes to different namespaces. As usual, feel free to use all of the code samples developed in this article, so you can extend your existing skills for using namespaces with PHP 5. Final thoughts In this second episode of the series, you hopefully learned how to tie a couple of basic sample classes that have the same name to different namespaces. As you saw before, this process is pretty intuitive, so you shouldn’t have major problems understanding how it works. In the upcoming article, I’m going to show you how to employ the “use” PHP keyword to declare several namespaces within the same application. Therefore, now that you’re aware of the topics that will be discussed in the next tutorial, you can’t miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|