php面向对象之——自动加载类

默认animal.php的代码如下:

<?php
class animal
{
   public $head;
   private $height;
   protected $width;
   public function __construct($height,$width)//属性和成员函数默认是public形式,所以public可以不用写
   {
       $this->height=$height;
	   $this->width=$width;
	   echo '<br>我是animal类构造函数的输出<br>';
   }
   public function move()
   {
       echo '<br>我是move方法的执行结果!<br>';  
   }
   function introduce()
   {
       echo '<br>我的高度是:'.$this->height;
	   echo '<br>我的宽度是:'.$this->width;
   }
   function __destruct()
   {
      echo 'animal类现在对象以及运行完,开始销毁了!';
   }
}
?>

  class.php的代码如下:

<?php
function __autoload($classname)
{
    if(file_exists($classname.'.php'))
	{
	   require_once($classname.'.php');
	}
	else
	{
	  echo '没有此类';
	}
}
$animal_obj=new animal('123','23');
//上面类的自动加载的原理为,当调用一个类并且这个类不存在时,会自动调用__autoload($classname),方法,其中$classname是没有找到的类名
?>

  也可以自定义__autoload($classname)函数;方法如下:

<?php
function me_autoload($classname)
{
    if(file_exists($classname.'.php'))
	{
	   require_once($classname.'.php');
	}
	else
	{
	  echo '没有此类';
	}
}
spl_autoload_register('me_autoload');//此行代码的作用为定义一个当加载一个没有定义的类时执行的函数名称为me_autoload,此时系统自动执行的__autoload函数就不会再调用;
$animal_obj=new animal('123','23');
?>

  在框架中常常用下面的方式:

<?php
class load
{
   public static function autoload($classname)
   {
         if(file_exists($classname.'.php'))
        {
           require_once($classname.'.php');
        }
        else
        {
          echo '没有此类';
        }   
   }

}
spl_autoload_register(array('load','autoload'));
//spl_autoload_register('load::autoload'); 这和上面一行是等价的
$animal_obj=new animal('123','23');
?>

 

posted @ 2013-03-08 17:39  qingq  阅读(210)  评论(0编辑  收藏  举报