Laravel:传递变量以在函数中作为全局变量进行查看和访问

时间:2019-04-06 06:33:51

标签: php laravel

我正在尝试将变量传递给视图,以便可以将其作为函数中的全局变量使用,但是它不起作用。我没有从函数中获得任何输出,但也没有收到错误消息。我要去哪里错了?

web.php

<?php
  Route::get('/', function() {
    $abc = 'abc';
    return view('front')->with(['abc'=>$abc]);
  });
?>

front.blade.php

<?php
  function fn() {
    global $abc;
    return $abc;
  }
?>

{{ fn() }}

3 个答案:

答案 0 :(得分:0)

您可以直接使用变量,而无需声明global

@php
  function fn() {
    return $abc;
  }
@endphp

{{ fn() }}

答案 1 :(得分:0)

使用dd助手:

@php
  function fn() {
    dd(get_defined_vars());
  }
@endphp

{{ fn() }}

了解更多:https://laravel.com/docs/5.4/helpers#method-dd

您可以通过以下操作进一步减少“无用”变量:

@php
  function fn() {
    dd(get_defined_vars()['__data']);
  }
@endphp

{{ fn() }}

答案 2 :(得分:0)

我发现可以做到的唯一方法是将变量作为参数传递给函数。

class Program
{
    public static void Main(string[] args)
    {
        List<string> Activewords = new List<string>();

        string guessWord = "183624911413";

        AddedWord(Activewords, guessWord, 0, "");
    }

    public static void AddedWord(List<string> Words, string searchWord, int Position, string curWord)
    {
        if (Position == searchWord.Length)
        {
            Words.Add(curWord);
            return;
        }

        char oneChar = searchWord[Position];
        int i = oneChar - 48;

        AddedWord(Words, searchWord, ++Position, curWord + (char)(i + 64));
        if (Position < searchWord.Length)
        {
            int j = i * 10 + searchWord[Position] - 48;

            if (j <= 26) //Alphabet has 26 letters
            {
                AddedWord(Words, searchWord, ++Position, curWord + (char)(j + 64));
            }
        }
         return ;
    }
}