将对象从一页移动到另一页?

2022-01-04 00:00:00 oop session post get php

伙计们.我对 PHP 中的 OOP 有点陌生.我已经学会了如何编写和创建对象.有没有办法获取一个对象并将其传递给另一个脚本?使用 GET 或 POST 或 SESSION 或其他.如果没有,我将如何在一个页面上为对象分配一些变量,然后在另一页上为同一对象分配更多变量?

Hay guys. I'm kinda new to OOP in PHP. I've learnt how to write and create objects. Is there a way to take an object and pass it to another script? either using GET or POST or SESSION or whatever. If there isn't how would i assign an object some variables on one page, then assign the same object more variables on another page?

谢谢

推荐答案

您可以在会话中存储对象,但您需要在调用 session_start() 之前包含包含类定义的文件(或使用 类自动加载 并在开始会话之前进行设置).例如:

You can store objects in the session but you need to include the file which contains the class definition before calling session_start() (or use class autoloading and set this up before you start the session). For example:

在每一页上:

//include class definition
require('class.php');

//start session
session_start();

第一页:

$object = new class();
$object->someProperty = 'hello';

//store in session
$_SESSION['object'] = $object;

后续页面:

$object = $_SESSION['object'];

//add something else, which will be stored in the session
$object->anotherPropery = 'Something';

相关文章