"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?
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: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
or us the ?? operator to set a default.