include的返回值

php有一个include,顾名思义,就是用来包含文件的。相应的还有require,以及两个带once的。不知道大家有没有注意过include的返回值。通常情况下,包含成功返回1,包含失败返回false。但是,如果被包含文件中用return返回,那么这个值就是return的值。比如:
//1.php
$ret = include ‘2.php’;
echo “$retn”; //输出wakaka
?>

//2.php
return ‘wakaka’;
?>

从1.php的输出就可以看到,这里include的返回值就是2.php中return的那个’wakaka’。

这个特性有什么用呢? 我是利用它来方便地使用php文件来做配置。比如,一个配置文件可以这么写:

//config.php
return array(
    ‘db’=>array(
            ‘host’ => ‘localhost’,
            ‘user’ => ‘root’,
            ‘password’ => ‘wakaka’,
            ‘name’ => ‘test’,
            ‘encoding’ => ‘utf8’
    )
);

载入的时候,只需要$conf = include ‘config.php’;就可以了。

 

2 thoughts on “include的返回值

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.