(新手)编写了2个函数,但一次又一次地出错

时间:2019-06-17 04:11:07

标签: php

我一直在尝试进一步学习PHP并每天编写函数进行练习,但是开始感到我要么过于复杂,要么做起来完全错误。

此脚本的2个功能:

function getFilesAndContent($path)
{
    $data = [];

    $folderContents = new DirectoryIterator($path);

    foreach ($folderContents as $fileInfo) {
        if ($fileInfo->isDot()) {
            break;
        }

        $fileData = [
            'file_name' => $fileInfo->getName(),
        ];

        if ($fileInfo->getExtension()) {
            $fileData['contents'] = getFileContents($fileInfo->getPathname());
        }

        $data = $fileData;
    }

    return $data;
}

function getFileContents($path)
{
    $names = file_get_contents($fileInfo->getPathname());

    $names = implode("\n", $names);

    sort($names);

    $contents = '';

    foreach ($names as $name) {
        $contents += $name . ' (' . strlen($name) . ')<br>';
    }

    return $name;
}

我要做的就是:

foreach (getFilesAndContent('.') as $data) {
    echo $data['file_name'];
    echo '<br>';
    echo $data['contents'];

    echo '<hr>';

错误: FATAL ERROR Uncaught Error: Call to undefined method DirectoryIterator::getName() in /home4/phptest/public_html/code.php70(5) : eval()'d code:15 Stack trace: #0 /home4/phptest/public_html/code.php70(5) : eval()'d code(45): getFilesAndContent('.') #1 /home4/phptest/public_html/code.php70(5): eval() #2 {main} thrown on line number 15

应该读取的文件是带有名称列表的简单.txt文件,仅此而已。

任何帮助表示赞赏!还想知道如果我继续收到这么多错误,最好重写整个函数是否更好?

1 个答案:

答案 0 :(得分:0)

您的代码中有许多要修复的事情,例如将未定义的方法getName()更改为其他内容,请不要使用break跳过,因为它会使用{{1}退出循环}通过分隔符分割字符串,从explode(string $separator, string $string)函数返回$contents以返回最终的串联字符串,等等。

我认为,您的目标是显示所有* .txt文件及其内容,内容中每一行的长度。试试这个:

getFileContents()