background image

 

注意:步骤 1 中的类的路径都是相对于 init.php 而言的,不是相对于 Utils 而言的,这是因
为我们通过 init.php 里的自动加载函数 spl_autoload_register 来

require

类的

代码如下:
 
<?php

require_once

 '/Utils/Utils.php';

final

 

class

 Init {

 

    

/**

     

* System config.

     

*/

    

public

 

function

 init() {

        

// error reporting - all errors for development (ensure you have

        

// display_errors = On in your php.ini file)

        error_reporting

 ( E_ALL | E_STRICT );

        

mb_internal_encoding ( 'UTF-8' );

        

//registe classes

        

spl_autoload_register ( 

array

 (

$this

,'loadClass' ) );

    

}

 

    

/**

     

* Class loader.

     

*/

    

public

 

function

 loadClass(

$name

) {

        

$classes

 = Utils::getClasses ();

        

if

 (! 

array_key_exists

 ( 

$name

$classes

 )) {

            

die

 ( 'Class "' . 

$name

 . '" not found.' );

        

}

        

require_once

 

$classes

 [

$name

];

    

}

}

$init

 = 

new

 Init ();

$init

->init ();

?>
 
3、本例中在使用处 test.php 里

require

 init.php

代码如下:
 
<?php

require_once

 'Init.php';

$dao

 = 

new

 UserDao();

$result

 = 

$dao

->findByName('zcl');

?>