PHP对象存入Session的方法
本示例详细解析了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();
}
?>
Click Here
最后编写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程序设计的实践能力。