PHP 5.3 introduces a much requested feature for object-oriented programmers: namespaces. At the time of this writing, version 5.3 of PHP was in development, but is planned on being released in the near future.
One of the purposes object-oriented programming is to remove ambiguous development and data access items. This basically means identifying common functionality and creating the most reusable framework possible, typically in the form of classes. When creating this functionality, you will begin to have issues with naming conventions and narrowing down functionality even further. To resolve this scoping issue, namespaces allow you to contain those bits of code even more.
It seems that PHP will be going with a similar namespace setup as C++. In order to declare a namespace, you will use the “namespace” keyword.
-
- namespace MyNamespace;
-
- class Test {
- public function hello() {
- }
- }
- ?>
The declaration above simply states that all elements contained in this script will be referenced with the “MyNamespace” namespace. You will need to place the “namespace” declaration at the top of the script.
In order to use a portion of functionality within this script, we will use the Scope Resolution Operator and instantiate the “Test” class.
-
- // Requiring the namespace file is a good indication that you don’t need to use namespaces, but this is only an example!
- require(‘the_file_above.php’);
- $test = new MyNamespace::Test();
- $test->hello();
- // Prints ‘hello’
- ?>
No comments:
Post a Comment