__autoload自动加载对象

自动加载对象

很多开发者写面向对象的应用程序时对每个类的定义建立一个 PHP 源文件。一个很大的烦恼是不得不在每个脚本(每个类一个文件)开头写一个长长的包含文件列表。

在 PHP 5 中,不再需要这样了。可以定义一个 __autoload 函数,它会在试图使用尚未被定义的类时自动调用。通过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

Note:

在 __autoload 函数中抛出的异常不能被 catch 语句块捕获并导致致命错误。

Note:

如果使用 PHP 的 CLI 交互模式 时,Autoloading 不存在。

 

Example #1 Autoload 例子

本例尝试分别从 MyClass1.php 和 MyClass2.php 文件中加载 MyClass1MyClass2 类。

<?php
function __autoload($class_name) {
    require_once 
$class_name '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>


构造函数和析构函数> <类常量 [edit] Last updated: Fri, 24 Feb 2012
 
reject note add a note add a note User Contributed Notes 自动加载对象
shaftouille 12-Jan-2012 01:14
I think there shouldn't be tests in an autoload callback function, this callback will trigger because the class you're trying to load is not defined... in any case if your class is not defined, the code must fail. Therefore an autoload function should be like :

<?php
spl_autoload_register
(function($className)
{
    require(
str_replace('\\', '/', ltrim($className, '\\')) . '.php');
});
?>

As the "require" function uses the include_path, the folders for the autoinclusion should be added using set_include_path, let's say your index.php is located in a "public" directory and your MVC classes are in "core", the index.php should be :

<?php
define
('ROOT_DIR', realpath(__DIR__ . '/..'));

set_include_path(ROOT_DIR . PATH_SEPARATOR . get_include_path());
?>

And of course you want to catch the loading errors, so you can use class_exists :

<?php
$className
= '\core\Controller\Hello\World';

if (!
class_exists($className))
{
    throw new
ErrorException('Class Not Found !');
}
else
{
   
$object = new $className();
}
?>

This code sample will autoload the "World.php" file located in your "core/Controller/Hello" directory, assuming that your class declaration is like :

<?php
namespace coreControllerHello
;

class
World
{
    function
__construct()
    {
        echo
"Helloworld";
    }
}
?>
qfox at ya dot ru 16-Nov-2011 02:48
More simpler example of using spl_autoload_register in 5.3:
<?php
spl_autoload_register
(function($classname) /* usign $app */ {
 
# ... your logic to include classes here
});
?>
Nic 25-Aug-2011 12:22
Autoloading camel case classes, ie. loading "controller/product/detail.php" from "ControllerProductDetail":

<?php
// Autoloading
function __autoload($class) {
   
$path = strtolower(preg_replace('/([a-z])([A-Z])/', '$1/$2', $class));
    if(
file_exists(DIR_APPLICATION . $path . '.php')) {
        require_once(
DIR_APPLICATION . $path . '.php');
    }
}
?>
bimal at sanjaal dot com 05-Jun-2011 11:58
When multiple scripts try to use __autoload(), there is a collision.
I experienced it while upgrading the Smarty and my own autoload function.

So, the better way is to avoid __autoload() and use spl_register_autoload() instead. If you have written this already, just rename your function to something like __autoload_my_classes, and in the next, call spl_autoload_register as:

<?php
function __autoload_my_classes($classname)
{
 
# ... your logic to include classes here
}
spl_autoload_register('__autoload_my_classes');
?>

You can assign multiple functions to spl_autoload_register() by calling it repeatedly with different function names. Be sure to limit your every function to include a CLASS file.
rahj_1986 at (yahoo) dot com 30-May-2011 10:22
in my case i use config.php and put all the settings there including the _autoload functions. Just include the config.php in all of your php file. Heres how:

config.php:

<?php

function __autoload($classname) {
   include_once(
"classfolder/" . $classname . ".php");
}

?>

ClassFolder: with SampleClass.php

<?php

class SampleClass {
   public function
hello_rahj() {
      echo
"Hello rahj!";
   }
}

?>

In your Typical Php File: e.g. Index.php

<?php

include("config.php")

$hello = new SampleClass();
$hello->hello_rahj(); // outputs Hello rahj!

?>

When using the __autoload functions, Make Sure you use a Proper naming Convention.

Hope this Helps!
superzouz at hotmail dot com 01-May-2011 04:19
After a while trying to get __autoload() to work, I used spl_register_autoload instead. __autoload() unexplainably failed so I gave up on it.
T dot Alexander Lystad tal at lystadonline dot no 11-Feb-2011 07:19
This is an example of how I used autoloading in my application:

<?php
spl_autoload_register
(function ($className) {
   
$possibilities = array(
       
APPLICATION_PATH.'beans'.DIRECTORY_SEPARATOR.$className.'.php',
       
APPLICATION_PATH.'controllers'.DIRECTORY_SEPARATOR.$className.'.php',
       
APPLICATION_PATH.'libraries'.DIRECTORY_SEPARATOR.$className.'.php',
       
APPLICATION_PATH.'models'.DIRECTORY_SEPARATOR.$className.'.php',
       
APPLICATION_PATH.'views'.DIRECTORY_SEPARATOR.$className.'.php',
       
$className.'.php'
   
);
    foreach (
$possibilities as $file) {
        if (
file_exists($file)) {
            require_once(
$file);
            return
true;
        }
    }
    return
false;
});
?>
b dot rense at gmail dot com 01-Dec-2010 08:54
php autoloading is a b*tch, nevertheless, i think the following class is a pretty good solution.

<?php

class autoload_autoloader {
    public static
$instance;
    private
$_src=array('application/controllers/', 'application/models/', 'application/views/helpers/', 'library/');
    private
$_ext=array('.php', 'class.php', 'lib.php');
   
   
/* initialize the autoloader class */
   
public static function init(){
        if(
self::$instance==NULL){
           
self::$instance=new self();
        }
        return
self::$instance;
    }
   
   
/* put the custom functions in the autoload register when the class is initialized */
   
private function __construct(){
       
spl_autoload_register(array($this, 'clean'));
       
spl_autoload_register(array($this, 'dirty'));
    }
   
   
/* the clean method to autoload the class without any includes, works in most cases */
   
private function clean($class){
        global
$docroot;
       
$class=str_replace('_', '/', $class);
       
spl_autoload_extensions(implode(',', $this->_ext));
        foreach(
$this->_src as $resource){
           
set_include_path($docroot . $resource);
           
spl_autoload($class);
        }
    }
   
   
/* the dirty method to autoload the class after including the php file containing the class */
   
private function dirty($class){
        global
$docroot;
       
$class=str_replace('_', '/', $class);
        foreach(
$this->_src as $resource){
            foreach(
$this->_ext as $ext){
                @include(
$docroot . $resource . $class . $ext);
            }
        }
       
spl_autoload($class);
    }

}

?>

Obviously you still have to include this class the dirty way, for example:

<?php

$path
='../';
$docroot=$_SERVER['DOCUMENT_ROOT'] . implode('/',array_slice(explode('/',$_SERVER['PHP_SELF']),0,-2)) . '/';
include(
$path . 'library/autoload/autoloader.php');
autoload_autoloader::init();

?>

please note that this autoloader class does require the $docroot variable which is the absolute path of the root of your application, you can set it manually or copy the code i used.

my directory structure looks like this:
- www/
    + myapp/
        + application/
            + controllers/
            + models/
            + views/
                + helpers/
        + library/
            + autoload/
                - autoloader.php
fka at fatihkadirakin dot com 31-Jul-2010 06:16
Or you can use this, without using any "require/include":

<?php
class autoloader {

    public static
$loader;

    public static function
init()
    {
        if (
self::$loader == NULL)
           
self::$loader = new self();

        return
self::$loader;
    }

    public function
__construct()
    {
       
spl_autoload_register(array($this,'model'));
       
spl_autoload_register(array($this,'helper'));
       
spl_autoload_register(array($this,'controller'));
       
spl_autoload_register(array($this,'library'));
    }

    public function
library($class)
    {
       
set_include_path(get_include_path().PATH_SEPARATOR.'/lib/');
       
spl_autoload_extensions('.library.php');
       
spl_autoload($class);
    }

    public function
controller($class)
    {
       
$class = preg_replace('/_controller$/ui','',$class);
       
       
set_include_path(get_include_path().PATH_SEPARATOR.'/controller/');
       
spl_autoload_extensions('.controller.php');
       
spl_autoload($class);
    }

    public function
model($class)
    {
       
$class = preg_replace('/_model$/ui','',$class);
       
       
set_include_path(get_include_path().PATH_SEPARATOR.'/model/');
       
spl_autoload_extensions('.model.php');
       
spl_autoload($class);
    }

    public function
helper($class)
    {
       
$class = preg_replace('/_helper$/ui','',$class);

       
set_include_path(get_include_path().PATH_SEPARATOR.'/helper/');
       
spl_autoload_extensions('.helper.php');
       
spl_autoload($class);
    }

}

//call
autoloader::init();
?>

你可能感兴趣的:(PHP,职场,休闲)