session传递对象或者类

user.class文件
PHP 代码:

<?php
/*
 * 用户类函数
 */
class USER {
    var $id;
    var $username;
    var $email;
    function user($userinfo) {
        $this->id=$userinfo[0];
        $this->username=$userinfo[1];
        $this->email=$userinfo[2];
    }
}
?> 

index.php文件
PHP 代码:

<?php
/*
 *  测试用
 *
 */
session_start();
include("conn.php");
include("user.class");
/*  初始化一个用户类 */
function initUser()
{
$userinfo[]=1;
$userinfo[]="thankwsx";
$userinfo[]="jiangsujier@163.com";
$user=new USER($userinfo);
return $user;
}
$your=initUser();
session_register("your");
echo "<pre>";
echo $your->username;
echo "</pre>";
?> 

session.php文件
PHP 代码:

<?php
/*
 * 测试session
 */
 include("user.class");
 session_start();

 echo session_is_registered("your")?"TRUE":"WRONG";
 echo "<pre>";
 var_dump($_SESSION);
 echo "</pre>";

$your=$_SESSION["your"];
echo $your->username;
?> 

最后一个文件很重要的一步,
你必须把类的定义放在session_start 前面,否则会得不到想要的结果。

随机日志

发表评论

0 评论.

Leave a Reply



[ Ctrl + Enter ]

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

CNXCT小组的博客 is Stephen Fry proof thanks to caching by WP Super Cache