Why does "fopen return" fail?

I have a function:

function open($file){
    return fopen($file, 'w');
}

      

Then it is called:

function write($file,$text){
    $h = $this->open($file);
    fwrite($h,$text);
}

      

This does not work. It returns that fwrite received an invalid resource stream.

It:

function open($file){
    $h = fopen($file, 'w');
    return $h;
}

      

Works well, but I can't figure out why variable assignment first works and fopen () returning directly doesn't work.

+1


a source to share


3 answers


Probably just because you are working in the scope of an object, so it cleans up the resource stream too early - since it passes the resource stream to byref, if you have a set of variables overriding it with a variable instead of trying to do it in the resource stream - so this will work ...



0


a source


Is it because you are inside an object? The script works for me:

<?php
        function open($file) {
                return fopen($file, 'w');
        }

        function write($file, $text) {
                $h = open($file);
                fwrite($h, $text);
        }

        write("test.txt", "hello\n");

?>
      



I am running PHP 5.2.8 on Mac OS X 10.5.7.

+1


a source


to announce

var $ file

then

$ this-> file = fopen (...)

return $ this-> file;

this will work because the $ file variable is still referenced.

0


a source







All Articles