【问题标题】:how to save object state in php如何在php中保存对象状态
【发布时间】:2011-04-22 18:33:39
【问题描述】:

我有 3 个文件

  1. class.myclass.php
  2. test1.php
  3. test2.php

class.myclass.php 包含

class myclass
    {
    public $value;

    function assign($input)
        {
        $this->value=$input;
        }
    function show()
        {
        echo $this->value;
        }
    }

$obj=new myclass();

test1.php 包含

require("class.myclass.php");
$obj->assign(1);
$obj->show();

test2.php 包含

require("class.myclass.php");
$obj->show();

在 test2.php 中,方法 $obj->show(); 没有显示方法 $obj->assign(1); 在 test1.php 中分配的值

我认为当我运行 test2.php 时,对象 $obj 会再次创建,因此分配的值会消失。有什么方法可以保存对象的状态,所以我可以从其他 php 页面使用

您的帮助将不胜感激。谢谢!!

【问题讨论】:

    标签: php class object methods state


    【解决方案1】:

    最简单的方法是以序列化形式将对象保存在 $_SESSION 变量中,这样它就会在您网站上的点击之间自动保留。

    test1.php:

    session_start();
    require('class.myclass.php');
    $obj->assign(1);
    $_SESSION['myobj'] = serialize($obj);
    

    test2.php:

    session_start();
    $obj = unserialize($_SESSION['myobj']);
    $obj->show();
    

    对于这样一个简单的对象,这就是所需要的。如果您的对象包含资源句柄(mysql 连接、curl 对象等),那么当对象在反序列化时恢复时,您将需要一些额外的逻辑来处理恢复这些连接。

    但是,您可能需要重新考虑在类文件中自动实例化您的对象,或者至少将其变成一个单例对象,这样您的类文件就可以包含在多个位置,而无需最后一次 $obj 获取每次重新包含文件时都会被覆盖。

    【讨论】:

      【解决方案2】:

      我在项目中使用的一种技术是创建一个好的类构造函数。我的意思是创建一个构造函数,它可以使用单个参数重新创建相同的对象。

      例如:

      class User {
      
          public $email;
          public $username;
          public $DOB;
      
          function __construct($input) {
              // by providing a single input argument, we can re-create the object...
              $this->email    = $input;
              $userData       = $this->getUserData();
              $this->username = $userData['username'];
              $this->DOB      = $userData['DOB'];
          }
      
          function getUserData() {
              $email = $this->email;
              $array = ["username" => "", "DOB" => ""];
              // Database query/queries to get all user info for $email go here...
              return $array;
          }
      }
      

      现在,如果您将 $email 存储为 $_SESSION 变量,您可以重新创建对象,例如:

      file1.php

      <?php
          session_start();
          $email = "hi@example.com";
          $_SESSION['user'] = $email;
      

      file2.php

      <?php
          session_start();
          include('User.class.php'); // this is the class example above
          $email = $_SESSION['user'];
          $userObject = new User($email);
      
          // now you can access the object again as you need...
          // for example:
          $username = $userObject->username;
          echo "Welcome back " . $username;
      

      【讨论】:

        猜你喜欢
        • 2021-06-27
        • 2023-04-06
        • 2013-09-15
        • 1970-01-01
        • 2021-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多