尝试读取数组上的属性“title”错误异常Laravel Php

问题描述

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

**我来自应用程序/模型的邮政编码如下**

 <?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()
       );
    }
});

就我所知,代码是正确的,我只是不知道是否需要添加或执行某些操作来消除错误

解决方法

我认为错误确实在这里

function App() {
  const [jwtToken,setJwtToken] = useState(null);

  useEffect(() => {
      if(jwtToken){
       console.log("connect")
        var socket = io(getURL,{
          transports: ['websocket'],jsonp: false,'forceNew': true
        })
        socket.on("new-message",message => console.log(message))
      }
  },[jwtToken]);

我认为你可能需要这样做

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 循环内

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

特别在这里

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

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

$document->title,

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

$document[0]->title,

或者你可以把第一部分改写成

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...