When storing an object in $_SESSION trying to retrieve it in another page we will get an error if the class itself is not available when the session_start() function builds the $_SESSION array. Debugging the $_SESSION we will find that our object is available and is stored as a __PHP_Incomplete_Class object. In order to avoid this problem we better make sure that the class definition is available before we call the session_start() function by calling the require_once\require\include_once\include for getting the class definition in advance (before we call the session_start() function). Getting __PHP_Incomplete_Class object can happen in other similar scenarios, such as when calling the unserialize() function while the class definition is not available.

The following video clip uses a code sample composed of three files in order to demonstrate getting a __PHP_Incomplete_Class object.

The Rectangle.php file includes the definition for the Rectangle class.

<?php

class Rectangle
{
    private $width;
    private $height;
    function __construct($hVal,$wVal)
    {
        $this->setHeight($hVal);
        $this->setWidth($wVal);
    }
    public function setHeight($height)
    {
        if($height>0)
        {
            $this->height = $height;
        }
    }
    public function getHeight()
    {
        return $this->height;
    }
    public function setWidth($width)
    {
        if($width>0)
        {
            $this->width = $width;
        }
    }
    public function getWidth()
    {
        return $this->width;
    }
}

?>

The first.php file instantiates Rectangle and stores the new object into the $_SESSION super global array.

<?php
include_once 'Rectangle.php';
session_start();
$ob = new Rectangle(4,3);
$_SESSION['rec'] = $ob;
?>
<a href='second.php'>second</a>

The second.php file retrieves the Rectangle object back from the $_SESSION super global array and calls various functions on it.

<?php
require_once 'Rectangle.php';
session_start();
var_dump($_SESSION);
$temp = $_SESSION['rec'];
$width = $temp->getWidth();
$height = $temp->getHeight();
echo 'width='.$width.' height='.$height;
?>
The __PHP_Incomplete_Class Object in PHP PRO

Leave a Reply

Your email address will not be published. Required fields are marked *