__autoload( $class ) :
自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。
例子:
<?php 
#  比如这是test.class.php文件
class test { 
    function show() {
        echo 'hello world';
    }
}
?> 
<?php
#  这是index.php文件
function __autoload( $class ) {
    $file = $class . '.class.php';  
    if( is_file($file) ){  
        require_once($file);  
    }
} 
$obj = new test();
$obj->show();
?>运行index.php后正常输出hello world。
在index.php中,由于没有包含test.class.php.
在实例化test时,自动调用__autoload函数.
参数$class的值即为类名test,此时test.class.php就被引进来了。
在面向对象中这种方法经常使用,可以避免书写过多的引用文件,同时也使整个系统更加灵活。
spl_autoload_register(array(‘class_name','method_name')) :
这个函数与__autoload有与曲同工之妙!
例子:
<?php 
#  比如这是test.class.php文件
class test { 
    function show() {
        echo 'hello world';
    }
}
?> 
<?php
#  这是index.php文件
function load( $class ) {
    $file = $class . '.class.php';  
    if( is_file($file) ){  
        require_once($file);  
    }
}
#  不同调用写法
// spl_autoload_register('load'); 
// spl_autoload_register(array('test','load'));
spl_autoload_register("test::load"); 
$obj = new test();
$obj->show();
?>将__autoload换成load函数。
但是load不会像__autoload自动触发。
这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行load()。
转载请注明来源地址:小川编程 » https://www.youhutong.com/index.php/article/index/162.html
1、本站发布的内容仅限用于学习和研究目的.请勿用于商业或非法用途,下载后请24小时内删除。
2、本站所有内容均不能保证其完整性,不能接受请勿购买或下载,如需完整程序,请去其官方购买正版使用
3、本站联系方式Email:admin@youhutong.com ,收到邮件会第一时间处理。
4、如侵犯到任何版权问题,请立即告知本站(立即在线告知),本站将及时删除并致以最深的歉意
 
				 
		




