Mauro74
Mauro74

Reputation: 4826

php Call to a member function on a non-object

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

Answers (4)

Alex
Alex

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

Khez
Khez

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

Nanne
Nanne

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

ThiefMaster
ThiefMaster

Reputation: 318508

This means $block is not an object, probably it's NULL or false in some cases (nothing found).

Upvotes: 1

Related Questions