PHP流包装器错误

时间:2013-09-17 19:44:28

标签: php stream wrapper

我正在尝试编写“身份流包装器”。第一个目的是让PHP通过这个包装器进行传输,这将与PHP本身完全相同。第二种是修改这个包装器以便做出决策。

所以第一项工作是将stream_open()映射到fopen(),将stream_write()映射到fwrite(),依此类推。 fopen()映射似乎工作正常,但是当我尝试调用fwrite()时,由于某种原因,包装器的内部资源变为布尔值,并且无法写入文件。 fread()会发生同样的事情。

任何人都可以解释为什么以及如何避免/解决?感谢...

以下是我的脚本输出:

36: resource(6) of type (stream)
60: resource(7) of type (stream)
49: bool(true)
PHP Warning:  fwrite() expects parameter 1 to be resource, boolean given in /var/www/projects/stream/test.php on line 51
PHP Stack trace:
PHP   1. {main}() /var/www/projects/stream/test.php:0
PHP   2. fwrite() /var/www/projects/stream/test.php:62
PHP   3. IdentityStreamWrapper->stream_write() /var/www/projects/stream/test.php:62
PHP   4. fwrite() /var/www/projects/stream/test.php:51
63: resource(7) of type (stream)

这是它的代码(并不足以重现):

<?php

class IdentityStreamWrapper {
    var $fileHd;
    var $fileName;

    function __construct() {
      static::unwrap();
    }

    function __destruct() {
      static::wrap();
    }

    static function unwrap() {
        stream_wrapper_restore("file");
    }

    static function wrap() {
        stream_wrapper_unregister("file");
        stream_wrapper_register("file", "IdentityStreamWrapper");   
    }

    function stream_open($path, $mode, $options, &$opened_path)
    {
        if ($options >0) {
          $tOptions = $options;
          $tOptions = ($tOptions > STREAM_USE_PATH) ? ($tOptions - STREAM_REPORT_ERRORS) : $tOptions;
          if ($tOptions === STREAM_USE_PATH) {
            $opened_path = realpath($path);
          }
        }
        $this->fileName = $path;
        $this->fileHd = fopen($path,$mode);
        $this->position = 0;
echo __LINE__.": ";
var_dump($this->fileHd);
        return $this->fileHd;
    }

    function stream_write($data)
    {
echo __LINE__.": ";
var_dump($this->fileHd);
        $ret = fwrite($this->fileHd,$data);
        return $ret;
    }

}

IdentityStreamWrapper::wrap();

$fp = fopen("test.txt", "w+");
echo __LINE__.": ";
var_dump($fp);
fwrite($fp, "line1\n");
echo __LINE__.": ";
var_dump($fp);

IdentityStreamWrapper::unwrap();

?>

1 个答案:

答案 0 :(得分:0)

方法stream_open必须返回一个布尔值,而不是fopen()。这就是修复课程的全部内容。