0

I am having problem fetching return value returned by a class function in PHP. Does returning values works exactly the way it works in other languages- C, C++, Java or there is something new to it.

This is my Class:

class M_UserMaster
{

    private $_db = null;

    function __construct($db)
    {
        $this->_db = $db; 
    }


    function checkUserExists($mobNum)
    {
        $userExists = false;

        $sql = "SELECT STATEMENT HERE";

        $stmnt = $this->_db->prepare($sql);
        $stmnt->execute();

        $numRows = $stmnt->rowCount();

        echo '<br><br>Num Rows: ' . $numRows . '<br>***';

        $userExists = ($numRows > 0) ? true : false;

        return $userExists;
    }
}

The echo statement returns 0. But the function returns nothing.

From another file I am calling it like this:

$m_userMaster = new M_UserMaster($db);
$userExists = $m_userMaster->checkUserExists('0000000000');

echo '<br><br>User Exists: ' . $userExists;

This is what is printed

User Exists:

0

3 Answers 3

1

If you do

$x = true;
echo $x;

You will get output 1

But with

$x = false;
echo $x;

You will get empty string as output

You will need to do something like this:

echo '<br><br>User Exists: ' . ($userExists ? 'yes' : 'no');

Or change return value of your function from true / false to 1 / 0. That will behave similar way, but output will be correct.

Sign up to request clarification or add additional context in comments.

Comments

1

You are trying to echo a literal boolean value. PHP prints such values as empty strings. You want to do something like this, instead:

echo '<br><br>User Exists: ' . ($userExists ? 'true' : 'false');

This will echo the first part no matter what. It then checks whether $userExists is true. If so, it prints true; otherwise, it prints false.

Comments

1

Try like

$userExists = ($numRows > 0) ? 'true' : 'false';

As per your code,if the $numRows is greater than 0 then it will return 1 and if the $numRows is 0 then it will return empty because it become false.For clear understand

echo true;    // Return 1
echo false;   // Return empty

1 Comment

Goodness me that was funny coz all this time I used functions which returned true or false and not 'true' or 'false'. But they were not in classes- Does that make the difference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.