Search This Blog

Sunday, February 6, 2011

Include / Require in PHP 5.3 with Namespace

Chinese edition of this article

PHP 5.3 introduces a new feature: Namespace, which brings some trouble with Include / Require statement.

Before Namespace, we use Include / Require like this:
  1. Set proper include_path
  2. Each class per file with same file name as 'classname.php'
  3. Require_once 'filename.php' (simply without absolute path)
  4. Additionally, use __autoload function, also without absolute path
So the system will work and without relying specified path.

But namespace breaks the rule.

If you did as old way under namespace system, this may happen:
  1. \namespace1\class
  2. \namespace2\class
Statement require_once 'class.php' would not work.

Now in __autoload function, class / interface names are brings as format: namespace\classname (interface name), and if you simply put all include files into one folder, and follow the old naming rule: classname.php, naming collision will happen ( Same class name in different namespace ).

So, new way should be introduced:
  1. Put your class / interface files into folders according to its namespace, the file tree may like:
    • include
      • namespace 1
        • sub-namespace A
      • namespace 2
      • ...
  2. Use absolute path, if include / require files manually. Because relative path depends on order of include_path, and may cause same name class file in different namespace be included. Magic constant __DIR__ or __FILE__ may be useful to form the path.
  3. In __autoload function, form the path according to namespace respectively, also __DIR__ and __FILE__ may be help, if the file contains __autoload function is in proper folder too.
By this way, the include / require should work well with namespaces.

P.S.

I think the new feature brings too complex include / require / __autoload function into PHP, hoping the designers of PHP could do something to simplify it.

No comments:

Post a Comment