使用spl_autoload_register
,可以自动加载类。让我们举一个使用两个文件的简单示例:
索引.php
<?php
spl_autoload_extensions (".php");
spl_autoload_register ();
$class = new \kitchen\oven;
var_dump ($class);
var_dump (new kitchen\Microwave);
var_dump (new kitchen\Oven);
?>
厨房/烤箱.php
<?php
namespace kitchen {
class Microwave {
private $potency;
public function get_potency () {return $this->potency;}
public function set_potency ($potency) {$this->potency = $potency;}
}
class Oven {
private $temperature;
public function get_temperature () {return $this->temperature;}
public function set_temperature ($temperature) {$this->temperature = $temperature;}
}
}
?>
运行$ php index.php
给出以下输出:
object(kitchen\Oven)#1 (1) {
["temperature":"kitchen\Oven":private]=>
NULL
}
object(kitchen\Microwave)#2 (1) {
["potency":"kitchen\Microwave":private]=>
NULL
}
object(kitchen\Oven)#2 (1) {
["temperature":"kitchen\Oven":private]=>
NULL
}
一切都很好,我唯一关心的是命名法。我*必须*用该文件中任何类的相同名称提名我的文件。有什么方法可以让我使用更通用的名称吗?我希望我可以使用“kitchen/objects.php”而不是“kitchen/oven.php”。
谢谢。