Laravel blade global variable

2020-07-23 03:51发布

I have a problem in global variables in laravel. I know about view composer and my question is not related to that subject. How can I do such a simple thing in laravel view (*.blade.php | .php) template engine? for example this is a sample code from one of my views (.blade.php | *.php):

<?php
   function myFunc() {
     global $myvar;
     if ( ! $myvar ) {
       $myvar = 'my var is empty';
     }
     dd( $myvar );
   }

  $myvar = 'my var value';
  myFunc();

At the end of the execution it shows up 'my var is empty' and not 'my var value'. Anybody knows why this happens?

3条回答
一夜七次
2楼-- · 2020-07-23 04:06

In Laravel you can pass values from your included sub-blade to your main blade by declaring the variable you wish to pass values with as global in both the main and sub view. The key is declaring the passing variable as global on both ends (i.e., in both the main and included blade).

For instance:

INCLUDED SUB-BLADE

<? global $monetary_total; ?> <!-- somewhere up top of your sub-blade declare your variable as global scope  -->

@foreach ($monetary_assets_joint as $monetary_asset)

.... your code that cycles through rows and pulls a value...

<td>{{$monetary_asset->monetary_asset_value}} </td> <!-- somewhere you'll display the pulled values -->

... rest of your view code and markup ....

<?php $monetary_total += $monetary_asset->monetary_asset_value; //summing up pulled row value into passing variable ?>  

@endforeach

MAIN BLADE:

<? global $monetary_total; ?> <!-- somewhere up top of your blade declare your variable as global scope  -->

...

@include('partials.sub_blade') <!--  somewhere you include your sub-blade -->

...

{{$monetary_total}}  <!-- display summed total from included sub-bade's rows -->

Hope this helps.

查看更多
Viruses.
3楼-- · 2020-07-23 04:25

The best solution is to use the Config facade. You can create a new config file and set, in your case, global variables statically. But the best feature of this facade, are the get() and set() methods, which allow you to define these variables dynamically. See: Set Global variables in Laravel 5

In your case:

<?php
function myFunc() {
 $myvar = Config::get('vars.myvar');
 if ( ! $myvar ) {
   $myvar = 'my var is empty';
 }
 dd( $myvar );
}

Config::set('vars.myvar');
myFunc();

Make sure you import the Config facade by using use on the top of your file.

查看更多
手持菜刀,她持情操
4楼-- · 2020-07-23 04:29

Finally I found my answer, it has scope issue. because laravel uses class and methods to retrieve view so based on this page inforamtion: http://php.net/manual/en/language.variables.scope.php#98811

so we can write the code like this:

<?php
   function myFunc() {
     global $myvar;
     if ( ! $myvar ) {
       $myvar = 'my var is empty';
     }
     dd( $myvar );
   }

  global $myvar; // This line is the key
  $myvar = 'my var value';
  myFunc();
查看更多
登录 后发表回答