Home arrow PHP arrow Page 2 - Using Namespaces in PHP 5

The need to use namespaces in PHP 5 - PHP

Namespaces were created as part of PHP 5.3 to solve certain conflicts that can arise when two different classes are given the same name. This situation comes up more commonly than you might think. This four-part series introduces you to using namespaces to solve these and similar issues. It includes copious code examples to enhance your understanding.

TABLE OF CONTENTS:
  1. Using Namespaces in PHP 5
  2. The need to use namespaces in PHP 5
  3. Tying a PHP class to a namespace with the namespace keyword
  4. Working with a PHP class tied to a specific namespace
By: Alejandro Gervasio
Rating: starstarstarstarstar / 9
November 12, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

A good way to start explaining how to utilize namespaces with PHP 5 consists of recreating a simple - yet potentially real -- situation, where the name of a given class can be shared by another. In this case, suppose that there's a class called "User" which stores common user-supplied data, such as first and last names, as well as the corresponding email addresses.

The prototypical signature of a class like the one described above would look like this:


// define 'User' class


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;

}

}


Undoubtedly, the signature of the above "User" class is quite easy to grasp, since this class simply stores the full name and the email address of a fictional user on a few properties. In addition, the class implements some accessors, used directly for retrieving the values of these properties when required.

Now that you've seen how this sample class has been defined, here's an example that demonstrates how to use in a concrete case. Take a look at the following code sample, please:

// example on using the previous 'User' class without namespaces


try{

// create new instance of 'User' class

$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 output

First Name: Alejandro

Last Name: Gervasio

Email: alejandro@domain.com

*/

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


Actually, I don't want to be accused of being too selfish, but as you can see in the previous example, I utilized the "User" class to save my first and last names, as well as my email address as plain class properties. Once that task has been accomplished, these values are echoed to the browser via the respective accessors. That was really simple to code and understand, wasn't it?

So far, everything looks pretty good here, since this basic class does a decent job, particularly when it comes to handling user-supplied data. However, this seemingly peaceful scenario can turn quickly into a raging storm if I decide to work in conjunction with a third-party content management system, which also includes a class named "User."

How can these classes be used within the same PHP application, without having to waste time renaming one of them?

Well, the answer to that question is simply by using namespaces! With namespaces, it would be possible to specify that one "User" class belongs to a concrete namespace, called for example "General," while the second one would belong to a different namespace, named "CMS." Are you starting to see the benefits of using namespaces? I bet you are!

However, if you're anything like me, then you'll want to see how namespaces can be used with some functional PHP code. Therefore, bearing in mind this possibility, in the section to come, I'm going to show you how to utilize the previous "User" class so it can be tied to a predefined namespace.

To learn the full details of how this process will be accomplished, please click on the link that appears below and keep reading.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: