1

嗨伙计们,你能帮我下一步吗?

我有下一个代码

索引.php

set_include_path(get_include_path()
            .PATH_SEPARATOR.'application/controllers'
            .PATH_SEPARATOR.'application/models'
            .PATH_SEPARATOR.'application/views');
spl_autoload_register();
$front = new Controller;
$front->route();

控制器.php

public function route(){
    if(class_exists($this->getController())){...}......

我有一个办法。Insted 使用spl_autoload_register();I can write

function __autoload($classname) {
 @include_once $classname.'.php';
}

但是根据 php 文档,我想使用 spl_autoload_register... 如果您需要完整的代码,我很乐意演示它。

谢谢!

4

3 回答 3

1

你可以只使用file_exists,我想......

http://php.net/manual/en/function.file-exists.php

if( file_exists( 'path/to/' . $classname / '.php' ) )
{
  include_once( $classname.'.php' );
}

为什么要自动加载不存在的类?

你也可以试试这个:

if( !include_once( $classname.'.php' ) )
{
  //throw error, or do something... or nothing
  throw new Exception( "Autoload for $classname failed. Bad path." );
}
于 2012-04-03T20:05:47.830 回答
1

这是我使用的代码(我希望它会给你一个想法):

<?php
Class ClassAutoloader {

  function __construct() {
    spl_autoload_register(array($this, 'loader'));
  }

  private function loader($className) {

    $classPath = dirname(__FILE__).DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR;
    if(file_exists( $classPath.strtolower($className).'.php' )) {
      include $classPath.strtolower($className).'.php' ;
    } else if(file_exists( $classPath.$className.DIRECTORY_SEPARATOR.strtolower($className).'.php' )) {
      include $classPath.$className.DIRECTORY_SEPARATOR.strtolower($className).'.php';
    }
  }
}
于 2012-04-03T20:13:11.943 回答
0

你可以关闭错误

 <?PHP 
 error_reporting(E_ALL & ~E_WARNING)
 ?>
于 2012-04-03T20:05:07.980 回答