使用php的spl函数spl_autoload_register(mixed)
//同很多注册函数一样,spl_autoload有多种注册方式
//php自带的自动装载函数
// function __autoload($class) {
// include_once 'classes/' . $class . '.class.php'; //受用include_once,防止重复导入
// }
function my_autoloader($class) {
include_once 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
//使用匿名函数进行注册
spl_autoload_register(function ($class) {
include_once 'classes/' . $class . '.class.php';
});
?>
也可以使用类方法
/wwwroot/webapp/classes/User.class.php
class User
{
const DISCRIPTION = 'User Class';
public static $classID = 1024;
private $name;
private $age;
private $gender;
public function __construct($name,$age,$gender)
{
$this->name = $name;
$this->gender = $gender;
$this->age = $age;
}
public function __set($property_name,$property_value)
{
if(property_exists(__CLASS__,$property_name))
{
$this->$property_name = $property_value;
}
else
{
$this->$property_name = $property_value;
}
}
public function __get($property_name)
{
if(property_exists(__CLASS__,$property_name))
{
return $this->$property_name;
}
else
{
return 'undefined';
}
}
public function __toString()
{
return self::DISCRIPTION;
}
public function __destruct()
{
//echo '
'.self::DISCRIPTION.'['.self::$classID.']'.'@destroy';
unset($this->name);
unset($this->age);
unset($this->gender);
}
}
/wwwroot/webapp/UserAction.php
class SPL_EXTEND
{
public static function autoload($class)
{
include_once 'classes/' . $class . '.class.php';
}
}
//这里直接使用类方法注册
spl_autoload_register(array('SPL_EXTEND','autoload'));
$u = new User('zhangsan',20,'男');
$u->name = 'lisi';
$u->undefined = 'undefined';
echo $u->test;
echo User::DISCRIPTION;
echo $u;
?>