0

I have the following php code:

<?php

class Session {

    public function __construct() {
        if (!session_id()) {
            session_start();
        }
        if (!is_array($_SESSION['messages'])) {
            $_SESSION['messages'] = [];
        }
        echo is_array($_SESSION['messages']);
    }

    public function AddMessage($msg="") {
        array_push($_SESSION['messages'], $msg);
    }

    public function GetMessages() {
        $messages = $_SESSION['messages'];
        unset($_SESSION['messages']);
        return $messages;
    }

}

$session = new Session();

?>

And the output of $session->AddMessage('message') is:

1 
Warning: array_push() expects parameter 1 to be array, null given in ...\Session.php on line 16

so is_array clearly says that $_SESSION['messages'] IS an array. What am I missing?

6
  • I am not able to reproduce your error, this is usually caused by missing information in the question. Are you calling the $session->AddMessage('message') immediately after $session = new Session()? Commented Jan 21, 2016 at 18:37
  • Did you happen to call GetMessages() before AddMessage()? Commented Jan 21, 2016 at 18:38
  • Note: OP has edited the stackoverflow.com/revisions/34931400/1 Commented Jan 21, 2016 at 18:40
  • I made an edit. It's OK now. Commented Jan 21, 2016 at 18:45
  • 1
    @user3210615 No problem, actually you shouldn't update answer in your question. So that any future visitors might find the right answer from the answer section. not in the question itself Commented Jan 21, 2016 at 18:59

1 Answer 1

1

session_id is a function, so it should be:

    if (!session_id()) { //Not just session_id
        session_start();
    }

If you would have turned on error reporting it might have thrown:

Notice: Use of undefined constant session_id - assumed 'session_id'

Note: OP has edited the original question

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.