首页 > 解决方案 > 将类公共属性传递到视图文件并使用 $this 访问它们

问题描述

有没有办法使用$this从视图文件中访问 Controller 和 ChildController 的所有公共属性

<?PHP 

class Controller {

     public $userFamilyName = "Doe";

}

class ChildController extends Controller{

     public $user = "John"

     public function routeFunction(){
         return view("viewFile")
     }

}

查看文件 => viewFile.blade.php

<header>Hello {$this->user} {$this->userFamilyName} !</header>

标签: phplaravel

解决方案


您可以使用View::share$this 使您的视图文件中的属性可用

class ChildController extends Controller{

     public $user = "John"

     public function __construct()
     {
         \View::share('user', $this->user);
         \View::share('userFamilyName', $this->userFamilyName);
     }

     public function routeFunction(){
         return view("viewFile")
     }

}

现在可以在刀片中使用{{ $this->user }}.

阅读有关在视图中共享数据的更多信息: https ://laravel.com/docs/5.8/views#sharing-data-with-all-views


推荐阅读