php中将一个对象保存到Session中的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php中将一个对象保存到Session中的方法。分享给大家供大家参考。具体如下:

要保存对象到session其实很简单,我们可以使用session_register()函数,下面是使用范例

person_class.inc.php如下:

<?php
//
//File: person_class.inc.php
//Contains the class definition necessary to let an object be a session
//variable.
//
class Person
{
  var $name;
  var $email;
  //
  // A simple function to illustrate the point
  //
  function clean_name ()
  {
    $name = preg_replace("/h(.)+/i", "\\1", $this->name);
    return substr($name, 0, 15);
  }
}
?>

main.php文件如下:

<?php
//
//File: main.php
//Here is where we save and retrieve the object
//
include_once 'person_class.inc.php';
session_register('someperson');
if (!$someperson) {
  $someperson = new Foo;
  $someperson->name = "Item Raja";
  $someperson->email = "itemraja@php.net";
  $someperson->clean_name();
}
?>
<a href="somePage.php">Click Here</a>

somPage.php文件如下:

<?php
//
//File: somePage.php
//Print out the name without initializing the
//class and setting the variables
//
include_once 'person_class.inc.php';
session_register('foobar');
print $foobar->name;
?>

希望本文所述对大家的php程序设计有所帮助。

相关文章

PHP JSON格式数据交互实例代码详解

在PHP中解析JSON主要用到json_encode和json_decode两个PHP JSON函数,比PHP解析XML方便很多,下面详细介绍下PHP JSON的使用。JSON基础介绍...

很让人受教的 提高php代码质量36计

1.不要使用相对路径 常常会看到: require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前...

PHP中用header图片地址 简单隐藏图片源地址

复制代码 代码如下:<?php        $path=$_GET["path"];  ...

php中使用session防止用户非法登录后台的方法

本文实例讲述了php中使用session防止用户非法登录后台的方法。分享给大家供大家参考。具体如下: 一般来说,我们登录网站后台时,服务器会把登录信息保存到session文件里,并通过读...

php 获取可变函数参数的函数

func_num_args() 返回传递给该函数参数的个数 func_get_arg($arg_num) 取得指定位置的参数值,$arg_num位置index从0开始n-1。 func_...