PHP Auto Load file

Source: Internet
Author: User

In order to solve the problem of the introduction of multiple file pages and difficult to manage, PHP provides several automatic loading file scheme, which will be introduced here
Automatic load best to do class name and filename one to, Master pass by.

First, post the directory structure
method One: Use the __autoload () Magic function

app/home.php

<?php
class Home {public
    static function say () {
        echo ' hello ';
    }
}

autoload.php

Set_include_path setting contains the path function
//Path_separator delimiter '; '
Get_include_path () Gets the settings path

set_include_path (' app/'). Path_separator.get_include_path ());
function __autoload ($className) {
    include_once ($className. '). PHP ");
}
Home::say ();
method Two: Use Spl_autoload_register () spl:standard PHP Library standard PHP Libraries

app/home.php

<?php
class Home {public
    static function say () {
        echo ' hello ';
    }
}

autoload.php

Set_include_path (' app/'. Path_separator.get_include_path ());
Class AutoLoad {public
    static function load ($className) {
        include_once ($className. '). php ');
    }

Spl_autoload_register ([' autoload ', ' Load ']);
Can also be written as Spl_autoload_register (' autoload::load '); static mode

Home::say ();
Method Three: Spl_autoload_register () with namespace (required file name and class name one to)

autoload.php

Class AutoLoad {public
    static function load ($fileName) {
        $filePath = sprintf ('%s.php ', str_replace (' \ \ ', '/', $ FileName));
        Require_once $filePath;
    }
}
Spl_autoload_register ([' autoload ', ' Load ']);

lib/page.php

Namespace Lib;
Class Page {public
    static function show () {
        echo ' page ';
    }
}

app/home.php

Include_once ". /autoload.php ";

$p = new \lib\page ();
$p:: Show ();

Of course, it can be written

Include_once ". /autoload.php ";
Use Lib\page;

Page::show ();
$p = new page ();
$p->show ();

Thank you for your attention ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.