1

I have a function:

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

This is then called by:

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

This doesn't work. It returns that fwrite was given an invalid resource stream.

This:

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

Works fine, but I can't figure out why assigning a variable first works and directly returning fopen() doesn't.

2
  • I'm assuming this is all defined in a class? Could you show the entire class (or at least the relevant parts) together? It's kind of hard to help when they're out of context. Commented May 20, 2009 at 2:28
  • Yea, you need to give more information on where this snippet of code resides, because both ways work for me right now Commented May 20, 2009 at 2:45

3 Answers 3

1

Does it have something to do with the fact that you're within an object? The following 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'm running PHP 5.2.8 on Mac OS X 10.5.7.

Sign up to request clarification or add additional context in comments.

Comments

0

It's probably just because you are working in the scope of an object, so it cleans up the resource stream too early - since it passes a resource stream byref, if you have a variable set, its byref'ing the variable instead of trying to do it to the resource stream - so it'll work.

Comments

0

declare a

var $file

then

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

return $this->file;

this will works because the $file variable has still a reference.

Comments