[英]Call one function from another function in PHP class
I want to scan directories and subdirectories, make list of xml files, take content from xml files and display it. 我想扫描目录和子目录,制作xml文件列表,从xml文件中获取内容并显示它。 This functions work correctly without OOP.
此功能无需OOP即可正常工作。 I try to create a class.
我尝试创建一个类。 I call function
scandir_through
from function main
. 我从函数
main
调用函数scandir_through
。 I haven't errors, result too. 我没有错误,结果也是如此。
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();
?>
The problem is because the $dir
instance variable isn't what you're accessing within your main method. 问题是因为
$dir
实例变量不是您在main方法中访问的内容。 (It's looking for a $dir
variable in the scope of that method, rather than at the class level.) (它在该方法的范围内寻找
$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警告,你会发现它会抛出错误。
I think that $dir should be an argument for main. 我认为$ dir应该是主要的论据。 Just think if you had nothing else in the class, where would main get $dir from?
试想一下,如果你在课堂上没有别的东西,主要从哪里得到$ 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时,请包含dir,然后将其更改为:
$d->main($dir);
$items=data::scandir_through($dir);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.