Reputation:
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.
Upvotes: 1
Views: 348
Reputation:
declare a
var $file
then
$this->file = fopen(...)
return $this->file;
this will works because the $file variable has still a reference.
Upvotes: 0
Reputation: 285
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.
Upvotes: 0
Reputation: 60150
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.
Upvotes: 1