【问题标题】:Why global variable is being reset in Laravel controller为什么全局变量在 Laravel 控制器中被重置
【发布时间】:2019-01-22 15:33:22
【问题描述】:

我正在尝试全局设置一个变量,然后在其中添加值,但它正在被重置,见下文;

class NewTestController extends Controller
{
    private $attempted = [];
    public function nextQuestion(Request $request) {
        $this->attempted[count($this->attempted)] = $request->attempted;
        dd($this->attempted);
    }
}

如果我使用它本身的功能,它也会被重置。

【问题讨论】:

  • 如果你说的是$this->attempted,那么它不是一个“全局”变量;它是NewTestController 的属性,除非存储在会话中并在__construct() 中设置,否则每次调用nextQuestion() 时都可能会重置(取决于nextQuestion() 是什么以及它是如何工作的)。
  • 谢谢兄弟!但它再次被重置。我用过这个public function __construct() { $attempted = []; }
  • 嗯,在构造中应该是$this->attempted = [];,而不是$attempted ...,但就像我说的,如果你希望它在请求之间持续存在,你可能必须使用某种会话。我认为这个问题有点宽泛,我不能 100% 确定你在做什么。

标签: php laravel global-variables


【解决方案1】:

我已通过将新数据库设为attempted_questions 来解决我的问题,因此当尝试提问时,我将其存储到数据库中并检查它是否存在?使用数据库也比使用变量更方便,因为数据库不会像全局变量一样重置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多