Utilizing the Use Keyword for Namespaces in PHP 5

The release of PHP 5.3 is just around the corner. This version of the language comes with a lot of useful features that will put a smile on the face of many programmers. One major improvement it introduces is support for namespaces. This feature permits users to work independently with classes that share the same name, facilitating the development of object-oriented applications that use third-party libraries. Keep reading to learn more.

Introduction

So, if you’re a PHP developer who’s searching for an approachable guide on using namespaces with PHP 5, you’ve come to the right place. Welcome to the third installment of the series entitled “An Overview on Using Namespaces in PHP 5.” Comprised of four articles, this series walks you through the basics of working with namespaces in PHP 5-controlled environments, including the usage of the “namespace” and “use” keywords, and the implementation of namespaces aliases as well.

If you had the chance to read the preceding article of the series, then you’re probably familiar now with using namespaces in PHP 5. In that tutorial I explained how to link to sample classes that shared the same name to different namespaces. The immediate advantage in accomplishing this task was that the classes in question could be used independently within the same PHP script, without getting any errors from the PHP engine.

Definitely, namespaces allow you to solve in an elegant way any naming conflicts between classes that are used in the context of the same application, and as you learned in previous tutorials, they can be declared precisely by means of the “namespace” keyword. However, linking classes to specific namespaces by way of it requires writing more PHP code, since its syntax is pretty lengthy.

Fortunately, PHP 5 provides the “use” keyword, which can be employed to tie a given class to a particular namespace by using a shorter notation. Therefore, in this third part of the series, I’m going to code some illustrative examples for you that demonstrate the correct utilization of the “use” keyword.

Now it’s time to continue learning more useful aspects of using namespaces in PHP 5. Let’s get started!

{mospagebreak title=Review: linking two sample classes to different namespaces}

Before I start explaining how to utilize the “use” keyword to link a PHP 5 class to a specific namespace, it’d be pretty helpful to recall quickly how to perform the same task using the “namespace” reserved word instead.

The following example, which was developed in the previous tutorial, shows how to associate two sample classes named “User” to distinct namespaces, and how to work independently with two instances of these classes within the same PHP script.

Having said that, here is the complete set of source files required to get this introductory example working as expected:


(definition for ‘cmsuser.php’ file)


<?php

namespace UserManager::CMS;

 

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;

}

}

?>



(definition for ‘bloguser.php’ file)

 

<?php


namespace UserManager::Blog;

 

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;

}

// get all user data

public function getAll(){

return ‘First Name: ‘.$this->firstName.’ Last Name: ‘.$this->lastName.’ Email: ‘.$this->email;

}

}

?>



(definition for ‘index.php’ file)


<?php


// 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();

} 

?>


Here you have it. As you can see, the previous example shows how to use two different “User” classes independently in the same PHP script. In this concrete situation, the first of these sample classes has been linked to a “UserManager::CMS” namespace, while the second one has been tied to another, defined as “UserManager::Blog.”

At this moment you should feel pretty satisfied, since you hopefully recalled how to use the “namespace” keyword to associate a couple of sample classes to distinct namespaces.

Aren’t you really feeling that way? Okay, I know that you’re interested in learning how to perform the same process by utilizing the “use” reserved word. To learn the full details on how to achieve this, you’ll have to click on the link that appears below and keep reading.

{mospagebreak title=Introducing the use keyword}

For those programmers who suffer from chronic laziness and want to use a short syntax, PHP 5 provides yet another keyword, called “use,” which can be utilized to link one or more classes to a particular namespace.

In order to illustrate more clearly the utilization of this handy keyword, below I included another code sample. It shows how to tie the same “User” class that you saw in the previous section to a fictional “UserManager::Blog” namespace.


Here’s how this example in question looks:


// example on using the ‘use’ keyword

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;

}

}


As shown in the above hands-on example, the “use” keyword comes in handy for shortening the syntax required for declaring a namespace. In this case, a hypothetical “User::Manager” namespace has been linked to the sample “User” class that you learned before, but naturally this reserved word can be used with other classes.

Hopefully, the example that you just saw has been educational enough to demonstrate how to employ the “use” keyword in a useful manner when it comes to associating a concrete class to a particular namespace. However, I must admit that the example in question is still incomplete, since I haven’t shown you how to call an instance of a class that’s been linked to a namespace via the aforementioned keyword.

Therefore, the last section of this tutorial will be focused exclusively on explaining this process in depth. But, do you know how to get there? Click on the link shown below and keep reading!

{mospagebreak title=Working with an instance of the previous User class}

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!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort