If you're like me, then it's very probable that you may want to see how to work with an instance of the "User" class that you saw in the previous section. As you'll recall, it was linked to a "UserManager::Blog" namespace via the "use" keyword. The process is indeed very simple, as you'll see in a moment. First, I'm going to re-list the definition of the mentioned "User" class, along with the corresponding declaration of the namespace to which it belongs. Here it is: use UserManager::Blog::User;
class User{ private $firstName; private $lastName; private $email; public function __construct($firstName,$lastName,$email){ if(!$firstName||strlen($firstName)>32){ throw new Exception('Invalid First Name parameter!'); } if(!$lastName||strlen($lastName)>32){ throw new Exception('Invalid Last Name parameter!'); } if(!$email||!preg_match("/^.+@.+..+$/",$email)){ throw new Exception('Invalid Email parameter!'); } $this->firstName=$firstName; $this->lastName=$lastName; $this->email=$email; } // get user's first name public function getFirstName(){ return $this->firstName; } // get user's last name public function getLastName(){ return $this->lastName; } // get user's email public function getEmail(){ return $this->email; } } Now that I have linked the above class to the respective namespace, please take a look at the following script. It uses directly an instance of the class to display some basic information about myself: try{ // create new instance of 'User' class by using the specified namespace $user=new User('Alejandro','Gervasio','alejandro@domain.com'); // display user data echo 'First Name: '.$user->getFirstName().'<br />'; echo 'Last Name: '.$user->getLastName().'<br />'; echo 'Email: '.$user->getEmail().'<br />'; /* displays the following First Name: Alejandro Last Name: Gervasio Email: alejandro@domain.com */ } catch(Exception $e){ echo $e->getMessage(); exit(); } As you can see, when utilizing the "use" keyword, it's not necessary to specify the full path to the namespace linked to a given class. This obviously shortens the syntax required to accomplish this task, but when to employ "use" or "namespace" is something that depends entirely on your personal needs. With this last example, I'm concluding this overview on utilizing the "use" word, to work with namespaces in PHP 5. As always, feel free to tweak all of the code samples shown in this tutorial, to acquire a more solid grounding in this topic. Final thoughts In this third chapter of the series, I stepped you through working with the "use" keyword to shorten the code required to tie a class to a specific namespace. In the last article, you'll learn how to use aliases with namespaces, so now that you've been warned about the topics that will be discussed in this last part of the series, you simply can't miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|