Laravel Blade全局变量 [英] Laravel blade global variable
问题描述
我在laravel中的全局变量有问题.我了解View Composer,但我的问题与该主题无关. 如何在laravel视图(* .blade.php | .php)模板引擎中做这种简单的事情? 例如,这是我的一个观点( .blade.php | * .php)中的示例代码:
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?
推荐答案
最后,我找到了答案,它存在范围问题.因为laravel使用类和方法来检索视图,因此基于此页面信息: http://php.net/manual/zh/language.variables.scope .php#98811
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();
这篇关于Laravel Blade全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!