简体   繁体   English

如何在会话__PHP_Incomplete_Class对象中访问bean对象

[英]How to access bean objects in session __PHP_Incomplete_Class Object

I am creating a cart bean object in php and then storing it in session how ever when i tried to access the array of object from the session it always return one bean object only Here is bean class 我在php中创建一个购物车bean对象,然后将其存储在会话中,但是当我尝试从会话中访问对象数组时,它总是只返回一个bean对象,这是bean类

Class Cart{

private $quanity;
private $amount;

 function getQuantity() {
        return $this->quantity;
    }

    function getAmount() {
        return $this->amount;
    }

 function setQuantity($quantity) {
        $this->quantity = $quantity;
    }

    function setAmount($amount) {
        $this->amount = $amount;
    }

AddToCart.php AddToCart.php

$c = new cart();
$c->setAmount("500");
$c->setQuantity("10");

if(isset($_SESSION["cartArray"])){

    $ar = $_SESSION["cartArray"];
    $ar[]=$c;
    $_SESSION["cartArray"]=$ar;

}
else{
    $c;
    $_SESSION['cartArray']= [];
    $_SESSION['cartArray'][]=$c;
}

orderHandler.php orderHandler.php

$ar = $_SESSION["cartArray"];


foreach ($ar as $value) {
 echo '<pre>';
 print_r($value);
 echo '</pre>';

}

it gives me __PHP_Incomplete_Class Object and if try to write the following line in loop 它给了我__PHP_Incomplete_Class对象,如果尝试在循环中编写以下行

$echo $value->getAmount();

error: 错误:

Fatal error: main(): The script tried to execute a method or access a property of an incomplete object. 致命错误:main():脚本试图执行方法或访问不完整对象的属性。 Please ensure that the class definition "cart" of the object you are trying to operate on was loaded before unserialize() gets called or provide a __autoload() function to load the class definition 请确保在调用unserialize() 之前已加载要尝试操作的对象的类定义“购物车”,或提供__autoload()函数来加载类定义

The error message says it very clear: "Please ensure that the class definition "cart" of the object you are trying to operate on was loaded before unserialize() gets called" . 错误消息说得很清楚: “请确保在调用unserialize() 之前已加载要尝试操作的对象的类定义” cart”

What it fails to specify is that the function unserialize() is called behind the scene by the function session_start() to initialize the $_SESSION[] array. 无法指定的是,函数session_start()在后台调用了unserialize()函数来初始化$_SESSION[]数组。

You probably don't use an autoloader but manually include the needed files. 您可能不使用自动加载器,而是手动包含所需的文件。 If you were using an autoloader for your classes you wouldn't get the error in the first place. 如果您为类使用自动加载器,则首先不会出现错误。

The solution to your problem is quite simple: just make sure you include 'cart.php'; 解决问题的方法非常简单:只需确保include 'cart.php'; (the file that declares the class Cart ) before calling session_start() . (声明了class Cart的文件), 然后调用session_start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM