In order to solve the problem of the introduction of multiple file pages and difficult to manage, PHP provides several automatic loading file scheme, which will be introduced here
Automatic load best to do class name and filename one to, Master pass by.
First, post the directory structure
method One: Use the __autoload () Magic function
app/home.php
<?php
class Home {public
static function say () {
echo ' hello ';
}
}
autoload.php
Set_include_path setting contains the path function
//Path_separator delimiter '; '
Get_include_path () Gets the settings path
set_include_path (' app/'). Path_separator.get_include_path ());
function __autoload ($className) {
include_once ($className. '). PHP ");
}
Home::say ();
method Two: Use Spl_autoload_register () spl:standard PHP Library standard PHP Libraries
app/home.php
<?php
class Home {public
static function say () {
echo ' hello ';
}
}
autoload.php
Set_include_path (' app/'. Path_separator.get_include_path ());
Class AutoLoad {public
static function load ($className) {
include_once ($className. '). php ');
}
Spl_autoload_register ([' autoload ', ' Load ']);
Can also be written as Spl_autoload_register (' autoload::load '); static mode
Home::say ();
Method Three: Spl_autoload_register () with namespace (required file name and class name one to)
autoload.php
Class AutoLoad {public
static function load ($fileName) {
$filePath = sprintf ('%s.php ', str_replace (' \ \ ', '/', $ FileName));
Require_once $filePath;
}
}
Spl_autoload_register ([' autoload ', ' Load ']);
lib/page.php
Namespace Lib;
Class Page {public
static function show () {
echo ' page ';
}
}
app/home.php
Include_once ". /autoload.php ";
$p = new \lib\page ();
$p:: Show ();
Of course, it can be written
Include_once ". /autoload.php ";
Use Lib\page;
Page::show ();
$p = new page ();
$p->show ();
Thank you for your attention ~