
Namespace is the way to avoid the name collision. namespace, use and as are the keywords we use Namespace. The following is an example to show how to use the namespace.
// Define
namespace AppLib
// Call
require_once('lib.php');
echo AppLibFunctionName();
// Import namespace
use AppLib;
require_once('lib.php');
echo LibFunctionName();
// Namespace Alias
use AppLib as L;
require_once('lib.php');
echo LFunctionName();
Autoloading Namespaced Classes
This is an example to show how auto loading works
classesAppLib1MyClass.php
<?php
namespace AppLib1;
class MyClass {
public function WhoAmI() {
return __METHOD__;
}
}
?>
myapp.php:
<?php
use AppLib1MyClass as MC;
$obj = new MC();
echo $obj->WhoAmI();
// autoload function
function __autoload($class) {
// convert namespace to full file path
$class = 'classes' . str_replace('\', '/', $class) . '.php';
require_once($class);
}
?>
PSR-4 Autoloader
All the key word require, include or customized function __autoload try to fix autoload problem, but we still need a solution which is scallable and standardized, so all the framework and components can work well together. This is the purpose why PSR-4/Autoloader was designed.
The essensce of PSR-4 is mapping a top-level namespace prefix to a specific filesystem directory.
:: Operator
Double colon operator allow access to static, constant and overriden method of a class.
Interface vs Abstract Class
TBC
Credit:
Moden PHP




近期评论