首页 > 解决方案 > (新手)写了 2 个函数,但是一个接一个地出错

问题描述

我一直在尝试进一步了解 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 文件,仅此而已。

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

标签: php

解决方案


您的代码中有很多需要修复的getName()地方,例如将未定义的方法更改为其他方法,不要使用break跳过,因为它会退出循环,使用explode(string $separator, string $string)按分隔符拆分字符串,$contentsgetFileContents()函数返回以返回最终连接的字符串等。

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

$d = dir('.');
while (($file = $d->read()) !== false) { // iterate all files
    if (preg_match('/\.txt$/', $file)) { // filter only file ends with .txt
        $contents = explode("\n", file_get_contents($d->path . '/' . $file)); // get file contents, split by \n
        array_walk($contents, function(&$item) {
            $item .= ' (' . strlen($item) . ')';
        }); // add (length) in the end of each line

        // display it
        echo '<strong>' . $file . '</strong><br>';
        echo implode('<br>', $contents);
        echo '<hr>';
    }
}

推荐阅读