WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform
Using namespaces

Using namespaces

Every class and function in a namespace can be referred to by the full name - e.g. MyProject::DB::Connection or MyProject::DB::connect - at any time.

Example #1 Using namespaced name

<?php
    
require 'MyProject/Db/Connection.php';
    
$x = new MyProject::DB::Connection;
    
MyProject::DB::connect();
?>

Namespaces can be imported into current context (global or namespace) using the use operator. The syntax for the operator is:

<?php
/* ... */
use Some::Name as Othername;

// The simplified form of use:
use Foo::Bar;
// which is the same as :
use Foo::Bar as Bar;
?>
The imported name works as follows: every time that the compiler encounters the local name Othername (as stand-alone name or as prefix to the longer name separated by ::) the imported name Some::Name is substituted instead.

use can be used only in global scope, not inside function or class. Imported names have effect from the point of import to the end of the current file. It is recommended to put imports at the beginning of the file to avoid confusion.

Example #2 Importing and accessing namespace

<?php
    
require 'MyProject/Db/Connection.php';
    use 
MyProject::DB;
    use 
MyProject::DB::Connection as DbConnection;
    
    
$x = new MyProject::DB::Connection();
    
$y = new DB::connection();
    
$z = new DbConnection();
    
DB::connect();
?>

Note: The import operation is compile-time only, all local names are converted to their full equivalents by the compiler. Note that it won't translate names in strings, so callbacks can't rely on import rules.