2

当我尝试运行以下命令时,它会给出无法读取数组标题的错误异常。你能告诉我如何解决这个问题吗?

**我来自 app/models 的邮政编码如下 **

 <?php


namespace App\Models;

use Illuminate\Database\Eloquent\ModelNotFoundException; //
use Illuminate\Support\Facades\File;

class Post
{   
    public $title;

    public $excerpt;

    public $date;
    
    public $body;

    public function __construct($title, $excerpt, $date, $body)
    {
        $this-> title = $title;              //this is where the error is occurring 
        $this-> excerpt = $excerpt;
        $this-> date = $date;
        $this-> body = $body;
    }

    public static function all() 
    {
        $files = File::files(resource_path("postss/"));

      return  array_map(function ($file){
            return $file-> getContents();
        }, $files);
        
    
    }

    public static function find($slug)
    {
        
        base_path();

         if (!file_exists($path = resource_path("postss/{$slug}.html"))) {
            throw new ModelNotFoundException();
        }
    
        return cache()-> remember("posts.{$slug}", 7 , function () use ($path){
           
         return file_get_contents($path);
    
        });
    
    
        
      
       

    }


}

我的路线类代码是

Route::get('/', function () {
  
    $files = File::files(resource_path("postss"));
    $posts =[];

    foreach ($files as $file) {
       $document[] = YamlFrontMatter::parseFile($file);
       $posts[]= new Post(
           $document->title,
           $document->excerpt,
           $document->date,
           $document->body()
       );
    }
});

据我所知,代码是正确的,我只是不知道是否需要添加一些东西或做一些事情来使错误消失。

4

2 回答 2

2

我认为错误真的在这里

foreach ($files as $file) {
    // you load an array here !!!
    $document[] = YamlFrontMatter::parseFile($file);
    $posts[]= new Post(
       $document->title,        // then you use $document as a scalar?
       $document->excerpt,
       $document->date,
       $document->body()
   );
}

我想你可能需要做

foreach ($files as $file) {
   // you load an array here !!!
   $document = YamlFrontMatter::parseFile($file);
   $posts[]= new Post(
          $document->title,        
          $document->excerpt,
          $document->date,
          $document->body()
       );
}
于 2021-07-02T10:49:09.393 回答
2

错误在这个 foreach 循环中

foreach ($files as $file) {
   $document[] = YamlFrontMatter::parseFile($file);
   $posts[]= new Post(
       $document->title,
       $document->excerpt,
       $document->date,
       $document->body()
   );
}

专门在这里

$document[] = YamlFrontMatter::parseFile($file);

您将新对象添加到数组 $document 中并在此处

$document->title,

你尝试直接从 $document 访问标题,你需要指定数组的索引来访问具有属性的对象,像这样

$document[0]->title,

或者你可以将第一部分重写为

$document = YamlFrontMatter::parseFile($file);
于 2021-07-02T10:50:16.000 回答