简体   繁体   English

会话开始无效

[英]Session start doesn't work

Can Someone help me? 有人能帮我吗? Session start doesn't work. 会话开始无效。 What Am I doing wrong? 我究竟做错了什么? The error message is Fatal error: Uncaught Error: Call to a member function increment_index() on null 错误消息是致命错误:未捕获的错误:在null上调用成员函数crement_index()

This is my index.php 这是我的index.php

<?php

require 'config/bootstrap.php';

get_header();

$_SESSION = get_session_start_values();

dd($_SESSION['quiz']->increment_index());

render_fragment( 'quiz' );

get_footer();

This is my bootstrap file 这是我的引导文件

<?php
session_start();
require 'quiz.php';
require 'helpers.php';
require 'database.php';

And in my helpers I'm using this: 在助手中,我使用的是:

function get_session_start_values() {
    if ( ! isset( $_SESSION['quiz'] ) ) {
        return  [
            'quiz' => new Quiz(),
            'yes_no_questions' => 'yes_no_questions',
            'end_game' => false
        ];
    }
}

It would only work once because of this line: 由于此行,它只能工作一次:

if ( ! isset( $_SESSION['quiz'] ) ) {

Second time around, 第二次

$_SESSION = get_session_start_values();

sets $_SESSION to null $_SESSION设置为null

This should fix it: 这应该解决它:

function get_session_start_values() {
    if ( ! isset( $_SESSION['quiz'] ) ) {
        return  [
            'quiz' => new Quiz(),
            'yes_no_questions' => 'yes_no_questions',
            'end_game' => false
        ];
    }
    return $_SESSION;
}

$_SESSION is a super-global. $_SESSION是一个超级全局$_SESSION that is, you can just use it everywhere to access the session. 也就是说,您可以随处使用它来访问会话。 this includes the function where you set-up the initial values of the session: 这包括在其中设置会话初始值的函数:

function get_session_start_values() {
    if ( ! isset( $_SESSION['quiz'] ) ) {
        return  [
            'quiz' => new Quiz(),
            'yes_no_questions' => 'yes_no_questions',
            'end_game' => false
        ];
    }
}

Instead of asking for start values, just initialize if needed: 无需询问起始值,仅在需要时进行初始化:

function init_session_values(): void {
    if ( ! isset( $_SESSION['quiz'] ) ) {
        $_SESSION['quiz'] = new Quiz();
    }
    ...
}

Then just call the function when you mean it. 然后,在需要时调用该函数。 you don't need to take care of any return values. 您不需要照顾任何返回值。

<?php

require 'config/bootstrap.php';

init_session_values();

get_header();

This is much more straight forward to use and for what $_SESSION is made for (easy superglobal access). 使用$_SESSION可以更直接地使用它(用于轻松的全局全局访问)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM