开发者

Why use set_include_path() in PHP and how to autoload classes from different folders?

开发者 https://www.devze.com 2023-02-07 03:09 出处:网络
I have a couple questions about the include path in PHP and including files and/or classes. Below is a simple snippet of code where we are setting multiple i开发者_开发问答nclude paths.I saw this in

I have a couple questions about the include path in PHP and including files and/or classes.

Below is a simple snippet of code where we are setting multiple i开发者_开发问答nclude paths. I saw this in another project but I am not sure why?

I have never had to use set_include_path() in any of my projects over the last 5 years or so.

Q1)

So what exactly is the purpose of setting an include path? I have always just included the path in my include() call.

Q2)

In the example below it sets more then 1 path. How does this work for including files in multiple locations, i'm confused on the purpose or what it does exactly?

<?php
// Define App path
define('APPLICATION_PATH', realpath('../'));

// Build array of 3 different paths
$paths = array(
    APPLICATION_PATH,
    APPLICATION_PATH . '\com',
    get_include_path()
);


/*
Result of array above...
Array
(
    [0] => E:\Web Server\xampp\htdocs\test
    [1] => E:\Web Server\xampp\htdocs\test\com
    [2] => .;C:\php5\pear
)
*/

// Set include path from array above
// http://us3.php.net/manual/en/function.set-include-path.php
set_include_path(implode(PATH_SEPARATOR, $paths));

?>

Q3)

This is slightly different question but still relates to includes. Below is a simple autoload function for classes. I used to have a classes folder and autoload ALL my class files. In my current project, I have a library of classes to autoload like below does, but I then also have another section where I might need to autoload class files from a modules directory.

So I will need to autoload my library classes located somewhere like this....

root/includes/library/classes/library_class_files.php

+++plus+++

load classes for different modules (account, messages, friends, photos,blogs, forums, etc) located somewhere like this....

root/modules/forums/modules_class_files.php

I might not need to loads class files from the 2 different locations, but if I do, how would I go about doing that?

<?php
//auto include class files that we need on a per page basis
function __autoload($class_name){
    include('library/classes/' .$class_name . '.class.php');
}
?>


Q1: http://php.net/manual/en/ini.core.php#ini.include-path

Q2: As mentioned in the manual PHP iterates over every path and tries to find your file.

Q3: Using the more modern SPL Autoloader functionality you can define as many autoloaders as you like.

0

精彩评论

暂无评论...
验证码 换一张
取 消