I run a php script on a page which looks for certain classes/elements and I may sometimes get a “Trying to get property of non-object” error if the class/element does not exist.
I want to know how I can handle this error so that I can assign my own null value to a variable as using if statements or is_null does not seem to do the trick.
check out my code below for a better understanding of what I mean.
on the line if($size = $elem->find('.size',0)->plaintext) and error will be thrown for the ‘history’ element because the class size does not exist.
function:getInfo
function getInfo($link){
$page = file_get_html($link);
if($page){
$categoryLink = array();
$categoryName = array();
$categorySize = array();
if($container = $page->find('.infoContainer',1)){
foreach($container->find('.element') as $elem){
if($link = $elem->find('a',0)->href){
$categoryLink[] = $link;
}else{
$categoryLink[] = "";
}
if($name = $elem->find('.name',0)->plaintext){
$categoryName[] = $name;
}else{
$categoryName[] = "";
}
if($size = $elem->find('.size',0)->plaintext){
$categorySize[] = $size;
}else{
$categorySize[] = 0;
}
}
}
}
}
<div class='infoContainer'>
<div class='element'>
<a href='www.example.com/physics'>
<div class='name'>physics</div>
<div class='size'>1000</div>
</div>
<div class='element'>
<a href='www.example.com/math'>
<div class='name'>math</div>
<div class='size'>800</div>
</div>
<div class='element'>
<a href='www.example.com/history'>
<div class='name'>history</div>
</div>
</div>
call function
getInfo("www.example.com");
You should first check the result of
findbefore attempting to access its properties:This applies to all 3 checks inside the
foreach, only with different parameter names etc.