php会话变量

时间:2010-05-06 17:04:58

标签: php session

我的会话变量似乎不断丢弃其数组值。我能做错什么?这是我的目标吗?

session_start()从头开始,

if(isset($_SESSION['locations'])) { 
     unserialize($_SESSION['locations'])->listItems($_POST['companyLocation']); 
     echo "session exists"; 
}
else{
     $_SESSION['locations'] = serialize(new Location());
     unserialize($_SESSION['locations'])->listItems($_POST['companyLocation']);
     echo "session does not exist";
}        

class Location{

    function listItems($location){

    $array;

    $array[] = $location;

    //print_r($array);

    // Re-index:

    $array = array_values($array);

    print_r($array);

    $count = count($array);

    for ($i = 0; $i < $count; $i++) {

        echo "{$array[$i]}\n";

    }

    }

}

2 个答案:

答案 0 :(得分:4)

您在php脚本的开头是否有以下行?


<?php
session_start();
...

查看您的Location类,listItems函数看起来非常糟糕,您正在尝试做什么?

根据您的评论对您的Location类进行快速重构:


class Location {

    private $locations;

    public static function instance($args = null) {
        return empty($_SESSION['locations']) ? 
            new Location($args) : unserialize($_SESSION['locations']);
    }
    public function __construct($locations = null) {
        $this->locations = empty($locations) ? array() : $locations;
    }
    public function addLocation($location) {
        $this->locations[] = $location;
    } 
    public function listItems() {
        print_r($this->locations);
    }
    public function saveInstance() {
        $_SESSION['locations'] = serialize($this);
    }
}

用法是:


<?php
session_start();

$location = Location::instance();
if(!empty($_REQUEST['companyLocation']));
    $location->addLocation($_REQUEST['companyLocation']);
$location->listItems();
...
$location->saveInstance();
?>

答案 1 :(得分:2)

首先想到的是:

  1. 您是否记得在发送标题之前在每个页面的顶部使用session_start()?如果没有,则页面之间不存储会话信息。
  2. $_SESSION['locations']正在设置为一个对象。您从未对该对象进行序列化,这可能会导致尝试将其存储到会话中时出现问题。有关对象序列化的更多信息,请参阅http://www.php.net/manual/en/language.oop5.serialization.php,并将它们存储在会话对象中。