我想将文件引用作为函数参数传递。我不确定这在php中如何工作,但是在js中,只要变量是全局定义的,这似乎还可以。显然,这不是js,但是我不确定如何更改我的代码以解决此问题。
在文件的开头,我定义如下:
$myfileref = fopen('../some/path.txt', 'w');
function writeHeader($fileref){
fwrite($fileref, 'some text here\n');
}
Run Code Online (Sandbox Code Playgroud)
然后,我想这样称呼它:
writeHeader($myfileref);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这是我的代码:
<?php
$outfile = fopen('outfile.txt', 'w');
$path = '.';
$one_html = fopen('../write_dir/one.html', 'w');
if(!is_resource($one_html)){
die("fopen failed");
}
$two_html = fopen('../write_dir/two.html', 'w');
if(!is_resource($two_html)){
die("fopen failed");
}
$three_html = fopen('../write_dir/three.html', 'w');
if(!is_resource($three_html)){
die("fopen failed");
}
function searchFiles($dir){
$outpath = getcwd() . '/../write_dir/';
$in_dir = 'none';
$f_one = $f_two = $f_three = false;
$thisdir = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($thisdir, RecursiveIteratorIterator::SELF_FIRST);
global $one_html, $two_html, $three_html;
foreach($files as $object){
if($object->isDir()){
if(strpos($object->getPathname(), 'one') == true){
if(!$f_one){
echo "in one \n";
fileHeader($one_html);
$f_one = true;
}
$in_dir = 'one';
}
else if(strpos($object->getPathname(), 'two') == true){
if(!$f_two){
echo "in two \n";
fileHeader($two_html);
$f_two = true;
}
$in_dir = 'two';
}else if(strpos($object->getPathname(), 'three') == true){
if(!$f_three){
echo "in three \n";
fileHeader($three_html);
$f_three = true;
}
}
}
}
}
function fileHeader($fileref){
fwrite($fileref, "<table border=\"1\">\n");
fwrite($fileref, '<tr bgcolor=\"#CCCCCC\">\n');
fwrite($fileref, '<th>name</th>');
fwrite($fileref, '<th>description</th>');
fwrite($fileref, '<th>authors</th>');
fwrite($fileref, '<th>version</th>');
fwrite($fileref, '</tr>');
}
searchFiles('.');
?>
Run Code Online (Sandbox Code Playgroud)
将文件描述符(资源)传递给PHP中的函数没有任何魔术。它们将作为常规参数进行处理。
以下示例将按原样工作。(像你的)
<?php
// define your function
function write($fd, $message) {
fwrite($fd, $message);
}
// open a file
$fd = fopen('/tmp/a.txt', 'w');
// make sure that opening succeeded
if(!is_resource($fd)) {
die('fopen failed');
}
// write to the file
write($fd, 'hello world');
// close the file
fclose($fd);
Run Code Online (Sandbox Code Playgroud)
看到原始代码后进行更新:
您只是错过了将那些文件描述符作为参数传递给函数searchFiles。因此它们在的范围内不可用searchFiles()。请参考手册页面Variable Scope。
将函数声明更改为:
function searchFiles($dir, $one_html, $two_html, $three_html){
Run Code Online (Sandbox Code Playgroud)
并在调用时将这些值传递给函数:
searchFiles('.', $one_html, $two_html, $three_html);
Run Code Online (Sandbox Code Playgroud)
希望您了解自己做错了什么。