PHPに__autoload() とspl_autoload_register()使用メモ

1.説明

//__autoload概要
function __autoload($classname)
{
$filename = “./class/".$classname.".class.php";
if (is_file($filename))
{
include $filename;
}
}

//spl_autoload_register概要
spl_autoload_register('load_class’);

function load_class($classname)
{
$filename = “./class/".$classname.".class.php";
if (is_file($filename))
{
include $filename;
}
}

2.

使用例1

class ClassAutoloader {
public function __construct() {
spl_autoload_register(array($this, 'loader’));
}
private function loader($className) {
echo 'ロード中 ', $className, ' via ', __METHOD__, “()\n";
include $className . '.php’;
}
}

$autoloader = new ClassAutoloader();

$obj = new Class1();
$obj = new Class2();

使用例2

function a () {
include 'a.php’;
}
function b () {
include 'b.php’;
}
spl_autoload_register('a’);
spl_autoload_register('b’);

 

 

Source

Posted by arkgame