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中的Cannot modify header information 问题

完美解决PHP中的Cannot modify header information 问题

我就遇到这种问题,网上找到这个解决的方案,就收藏下写PHP的朋友们肯定遇到过这样一个问题:通过header函数改变http协议头的时候,会出现一个类似下面格式的warning:复制代码...

PHP设计模式之单例模式定义与用法分析

本文实例分析了PHP设计模式之单例模式。分享给大家供大家参考,具体如下: 单例模式(Singleton Pattern 单件模式或单元素模式),是常见的一种设计模式,它有三个特点...

PHP-FPM实现性能优化

简介: PHP-FPM 是一个 PHP FastCGI 管理器,一般 Nginx 上面跑 PHP 程序都会将 PHP 程序丢给 PHP-FPM 来解析。好了,就这样! PHP 5.4 开...

用PHP伪造referer突破网盘禁止外连的代码

比如我放纳米盘里的文件http://img.namipan.com/downfile/da333ee178bdad6531d1ec1540cf86277c116b6300887600/0...

一个显示某段时间内每个月的方法 返回由这些月份组成的数组

复制代码 代码如下: /** * 生成从开始月份到结束月份的月份数组 * 该方法仿照党子皓getDateArr()方法 * @param unknown_type $start * @p...