I know that you want to see how to use namespace aliases with PHP 5, but first I’d like to reintroduce the example developed in the preceding article of this series. It was aimed at demonstrating how to utilize the “use” keyword to tie a sample “User” class to a fictional “UserManager::Blog” namespace. That being said, here’s how the aforementioned example looked originally: 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; } } 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 by the above code sample, linking a class to a concrete namespace via the “use” keyword is indeed a no-brainer process that can be tackled with minor hassles. Naturally, the main advantage in using this reserved word in place of “namespace” is that it permits the use of a shortened syntax, but other than that, both of them have the same functionality. At this point, you've hopefully recalled how to associate a basic “User” class to a specific namespace, which means that it’s time to start explaining how to use namespace aliases to accomplish the same task. This useful topic will be discussed in depth in the section to come, so jump ahead and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|