Search code examples
phpstrict

PHP - E_STRICT: Creating default object from empty value


I see there are about a hundred different questions on here for Creating default object from empty value. None of them really seem to help with my issue.

I am assigning a child object of the same class in a method. This triggers the Creating default object from empty value error.

class myClass {


    function __construct($rootName, $allowHTML = false, $endTag = true) {
        $this->rootElement = $rootName;
        $this->elements = array();
        $this->attributes = array();
        $this->value = "";
        $this->allowHTML = $allowHTML;
        $this->endTag = $endTag;
        $this->styles = array();
        $this->childID = 0;
    }

    // ... OTHER METHODS HERE (ALL PROPERTIES DECLARED)

    function assignElement(&$theElement) {
        // Get the index.
        $index = count($this->elements);

        // Assign the element.
        $this->elements[$index] = $theElement;

        if (get_class($theElement) == get_class($this)) {
            $this->elements[$index]->childID = $index;
        }

        // Return the node.
        return $this->elements[$index];
    }
}

The error occurs on $this->elements[$index]->childID = $index;. How do I handle this properly?


Solution

  • Seems like you are passing NULL to the assignElement. get_class called with no arguments or null as argument, returns class of the object where it is defined, so your if conditions is true for null values. You should use is_object first.