"Trying to get property of non-object" error with PHP 7 (worked in PHP 5.4)

123

This is my function:

function get_cat_option($data, $pid, $cid=0, $parent=0){

    static $i = 1;
    $tab = str_repeat(" ",$i);
    static $a = 0;
    $pusher = "-";
    $showPusher = str_repeat($pusher,$a);
    if(isset($data[$parent]) && $data[$parent])
    {
        $html = "$tab";
        $i++;
        foreach($data[$parent] as $v)
        {

            $a++;           
            $child = get_cat_option($data, $pid, $cid, $v->category_id);
            if($v->category_parent_id == 0)
            {
                $listChild = "";
            }
            if($v->category_id == $pid)
            {
                $selected = ' selected';
            }
            else
            {
                $selected = '';
            }
            if($v->category_id == $cid)
            {
                $disabled = ' disabled';
            }
            else
            {
                $disabled = '';
            }
            $html .= "$tab";
            $html .= '<option value="'.$v->category_id.'"'.$selected.$disabled.'>'.$showPusher.' '.$v->category_title.'</option>';
            $a--;
            if($child)
            {
                $i--;
                $html .= $child;
                $html .= "$tab";
            }
        }
        $html .= "$tab";
        return $html;
    }
    else
    {
        return false;
    }
}

and I call it by:

<dt><select name="category" size="1" >
    <option value="">--</option>
    <?=get_cat_option($parent_data,$data['product_category'])?>
</select></dt>

Error is:

Trying to get property of non-object in

Error line is:

$child = get_cat_option($data, $pid, $cid, $v->category_id);   

This code worked perfectly in PHP 5.4 but now I'm using PHP 7.

How can I fix it?

793

Answer

Solution:

The error is most likely referring to the$v->category_id argument. Ifcategory_id doesn't exist in$v, then it throws an error.

Verify that your$data[$parent] object is correct before looping through it:

var_dump($data[$parent]);
484

Answer

Solution:

It is most likely that there is no property "category_id" in $v, so it is throwing a warning. You could check for its existance, using

if (isset($v->category_id)) {
// do something
}

or us the ?? operator to set a default.

$category_id = $v->category_id ?? $fallback;

People are also looking for solutions to the problem: How to transcode PHP uploaded videos into multiple qualities

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.