Check if the method is false and then the results are output

I have a class that contains a method that performs various database checks. Then it returns the value if it exists.

Here is an example of a basic setup:

PHP class

class myClass{

   var $aVar1;
   var $aVar2;

   function myMethod() 
   {
       // database query
       // if results from query return **results**
       // else return false
   }

}

HTML / PHP File

// setup $myClass object var

<?php if($myClass->myMethod(): ?>
    // lots of html
    <?php echo $myClass->myMethod() ?>
    // lots of html
<?php endif; ?>

This event occurs several times in my file with different ones methods. My question is that I call the method initially and check if it is false, and then call it again echo.

I could do the following, but in the end we get a variable declaration for each method. Should there be a more professional approach?

<?php 
$myMethod = $myClass->myMethod();
if($myMethod): ?>
    // lots of html
    <?php echo $myMethod ?>
    // lots of html
<?php endif; ?>

Is there a more efficient way to do this?

+4
source share
2 answers

. val

$result=$myClass->myMethod();
if($result!=FALSE)
  echo $result;

if($result=$myClass->myMethod())
echo $result;

!

echo $myClass->myMethod() ?: '';

, !

echo $result=$myClass->myMethod();
+3

, :

<?php

function foo($bool = true) {
    $result = array();
    if($bool) {
        $result = array('bar');
    }

    return $result;
}

if(! array()) {
    echo 'empty array evaluates to false.';
}

if($result = foo()) {
    var_export($result); // Will dump array with 'bar'.
}

if($result = foo(false)) {
    var_export($result); // Won't happen.
}

, if.

+2

All Articles