Zend_Loader::isReadable 和 is_readable 的区别

以前分析过 Zend Framework 1.0 的 Zend_Loader;php 内建函数 is_readable 本质上就是调用 filestat.c 的 php_stat 函数,这个在前几天关于 file_exists 和 is_file 的那个 post 中有说过。
今天在群上跟番茄吹水,说起来这个东西。于是又混一篇小记随便吹吹。
以下所有内容,45%是吹水,45%是猜测,10%是从代码中看出来的。

Zend_Loader:isReadable() 的代码如下:

150 /**
151 * Returns TRUE if the $filename is readable, or FALSE otherwise.
152 * This function uses the PHP include_path, where PHP’s is_readable()
153 * does not.
154 *
155 * @param string $filename
156 * @return boolean
157 */
158 public static function isReadable($filename)
159 {
160 if (!$fh = @fopen($filename, ‘r‘, true)) {
161 return false;
162 }
163 @fclose($fh);
164 return true;
165 }

可以看到,通过 fopen 来判断是否能访问指定文件。并且 fopen 的第三个参数为 true,也就是说允许判断 include_path 中的文件。这个方法有个显而易见的好处,除了可以判断 include_path 的文件外,还可以使用 http://foobar 或者 ftp://foobar 的 php stream 方式来判断是否可读。也就是说支持远端文件。

而 is_readable 从 php_stat 这个 c 函数的内容上可以看出,是不支持远端文件的。最多支持 file:// 而已。
不过 is_readable 是具有缓存的,也就是说可以用更小的代价去获得文件的访问属性。而 Zend_Loader::isReadable 不但要 fopen,还要 fclose 代价不能说不大了。

至于如何取舍,其实就看具体的需求了。

Leave a comment

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