array_push()期望参数1为数组,给定为null
问题描述:
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?
我有以下php代码: p>
&lt;? php
class Session {
public function __construct(){
if(!session_id()){
session_start();
}
if(!is_array($ _ SESSION ['messages'] )){
$ _SESSION ['messages'] = [];
}
echo is_array($ _ SESSION ['messages']);
}
公共函数AddMessage($ msg =“”) {
array_push($ _ SESSION ['messages'],$ msg);
}
公共函数GetMessages(){
$ messages = $ _SESSION ['messages'];
unset($ _ SESSION [ 'messages']);
返回$ messages;
}
}
$ session = new Session();
?&gt;
code> pre> \ n
$ session-&gt; AddMessage('message')的输出是: p>
1
警告:array_push()期望参数1为数组 ,在第16行的\ _ Session.php中给出null; n code> pre>
所以is_array清楚地说$ _SESSION ['messages']是一个数组。
什么是 我错过了? p>
DIV>
答
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