purpose
The purpose of this paper is to specify the namespace use keywords and new ClassName two steps, which step will be executed automatically load, which is a bit confusing logic of performance, this idea is normal, let's decrypt it
Namespace (namespace)
php joined from 5.3 namespace, I knows a bit about java, so the namespace is quite easy to understand why it needs namespace? Mainly to solve the class / function / constant internal conflicts write their own classes / functions / constants, and third parties
. Resource use have to use keywords such as indicated at reference namespace
require_once("apanly/BrowserDetector/Browser.php");
use apanly\BrowserDetector\Browser;
new Browser();
Automatically load
php can customize automatic loading function, mainly to reduce the use of include and require. E.g
function myLoader($classname){
$class_file = $classname . '.php';
if ( file_exists($class_file) ){
require_once($class_file);
}else{
echo "[ autoload error ]".$class_file." not found";
die(0);
}
}
spl_autoload_register("myLoader");
doubt
It is time to execute myLoader will automatically record function or a new use of an object when the function will be executed automatically load?
The answer is: new objects when a load function will be executed automatically
Example shows
use test
<?php
//根据class名字 找文件
function myLoader($classname){
$class_file = $classname . '.php';
if ( file_exists($class_file) ){
require_once($class_file);
}else{
echo "[ autoload error ]".$class_file." not found";
die(0);
}
}
spl_autoload_register("myLoader");
use \apanly\test\test;
new test();
No output
new test
<?php
//根据class名字 找文件
function myLoader($classname){
$class_file = $classname . '.php';
if ( file_exists($class_file) ){
require_once($class_file);
}else{
echo "[ autoload error ]".$class_file." not found";
die(0);
}
}
spl_autoload_register("myLoader");
use \apanly\test\test;
Output:
[ autoload error ]apanly\test\test.php not found
in conclusion
use only indicate that the use of the name space, new objects Barbara is automatic loaded trigger. Namespace and automatically load is not half dime
Reference material
Original Address: [php] namespace and automatically load the relationship
label: use the autoload namespace
Intelligent Recommendation
- [Android] No.2 Ionic package
- [] No.5 Ionic modify the application name, icon, start interface
- Composer: php dependency management tool
- PSR: php coding conventions
- [Java] one server to configure multiple Tomcat
Reproduced in: https: //my.oschina.net/54php/blog/794269