从 PHP 类中的另一个函数调用一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18132710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call one function from another function in PHP class
提问by vili
I want to scan directories and subdirectories, make list of xml files, take content from xml files and display it. This functions work correctly without OOP. I try to create a class. I call function scandir_through
from function main
. I haven't errors, result too.
我想扫描目录和子目录,制作 xml 文件列表,从 xml 文件中获取内容并显示它。此函数无需 OOP 即可正常工作。我尝试创建一个类。我scandir_through
从 function调用function main
。我没有错误,结果也是。
class data {
var $dir = 'D:\wamp4\www\begin';
public function scandir_through($dir)
{
$items = glob($dir . '/*');
for ($i = 0; $i < count($items); $i++) {
if (is_dir($items[$i])) {
$add = glob($items[$i] . '/*');
$items = array_merge($items, $add);
}
}
return $items;
}
public function main()
{
$scan_tree = $this->scandir_through($dir);
echo "<ul id='booklist'>"."</n>";
foreach ($scan_tree as $key=>$file){
$url = $file;
$xml = simplexml_load_file($url);
$book_count = count($xml->book);
for($i = 0; $i < $book_count; $i++) {
$book = $xml->book[$i];
$title=$xml->book[$i]->title;
$author=$xml->book[$i]->author;
//echo '</br>';
//echo $file. "   ";
//echo $title. "   ";
//echo $author;
echo "<li><div class='file'>".$file."</div>
<div class='title'>".$title."</div>
<div class='author'>".$author."</div></li></n>";
}
}
echo "</ul>";
}
}
$d = new data();
$d->main();
?>
回答by John Parker
The problem is because the $dir
instance variable isn't what you're accessing within your main method. (It's looking for a $dir
variable in the scope of that method, rather than at the class level.)
问题是因为$dir
实例变量不是您在主方法中访问的。(它正在$dir
该方法的范围内寻找一个变量,而不是在类级别。)
What you need to use is...
你需要使用的是...
$scan_tree = $this->scandir_through($this->dir);
If you turn on E_NOTICE warnings, you'll see that it'll have been throwing an error.
如果您打开 E_NOTICE 警告,您会看到它一直在抛出错误。
回答by user1522901
I think that $dir should be an argument for main. Just think if you had nothing else in the class, where would main get $dir from?
我认为 $dir 应该是 main 的一个论点。试想一下,如果你在课堂上没有其他东西, main 会从哪里得到 $dir ?
I would change:
我会改变:
public function main()
to
到
public function main($dir)
and when you call main using $d, include the dir so change that to:
当您使用 $d 调用 main 时,请包含目录,以便将其更改为:
$d->main($dir);
回答by Pichitron
$items=data::scandir_through($dir);