Reputation: 4826
I have this code:
function getBlockName($blockId){
$block = classContent::findById(conn(), $blockId);
echo $block->getBname();
}
now if the function outputs something works fine, if it doesn't output anything I have the
Fatal error: Call to a member function getBname() on a non-object in...
I'm pretty new to php so I couldn't find a solution on how to handle the error.
Any help would be very much appreciated! :)
Mauro
Upvotes: 0
Views: 2493
Reputation: 2122
Most likely it doesn't return an object if nothing was found.
function getBlockName($blockId){
$block = classContent::findById(conn(), $blockId);
if ($block !== false && is_object($block)) {
echo $block->getBname();
}
}
Edit: recommendation from comment.
Upvotes: 1
Reputation: 10350
Try testing for the result of $block
. In most cases you'd do:
<?php
function getBlockName($blockId){
$block = classContent::findById(conn(), $blockId);
if($block)echo $block->getBname();
}
?>
But I'm a little uncertain as to what findById returns. So here's something that's bound to work:
<?php
function getBlockName($blockId){
$block = classContent::findById(conn(), $blockId);
if(method_exists($block,'getBname'))echo $block->getBname();
}
?>
Upvotes: 0
Reputation: 64399
If your findById does not return anything, then $block is not an object. And you can not call members (getBnam()
) from something that is not an object. Hence the error.
You might want to add somecode to catch the event of not-returning anything.
like:
function getBlockName($blockId){
$block = classContent::findById(conn(), $blockId);
if(!$block){
echo 'error!;
}else{
echo $block->getBname();
}
}
Upvotes: 0
Reputation: 318508
This means $block
is not an object, probably it's NULL
or false
in some cases (nothing found).
Upvotes: 1