Forum Moderators: coopster

Message Too Old, No Replies

return false or return true

aren't returning a boolean

         

davelms

10:52 pm on Apr 3, 2006 (gmt 0)

10+ Year Member



Any hints or tips please?

PHP5. Class, Member function.

"return false;" or "return true;"

When checked in the code invoking the method nothing is returned. If I change to "return(0);" or "return(1);" then it works fine, and the value is returned ok - although obviously not technically a boolean.

I have tried all sorts, from

if ( memberfunction() ) {

or

if ( $val = memberfunction() ) {

or

$val = false;
$val = memberfunction();

(by the way, I appreciate the code above is lacking a few bits and bobs, its to show an example of what I have tried)

None work unless I use 0/1 instead of false/true.

Any guidance would be most appreciated. I have no problems with the use of false and true elsewhere expect via member functions.

Windows XP, Apache 2, PHP5.

THANKS!

coopster

12:26 am on Apr 4, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Are you passing the value back to a method within the class? You are likely going to have to offer more specifics here.

davelms

8:34 am on Apr 4, 2006 (gmt 0)

10+ Year Member



It's not "working" in many examples - hence my attempt to simplify maybe went too abstract, sorry - but here is one just for example:

User class is a singleton.

$user = User::instance();
if ( $user->changePassword($password) ) {
... etc ...
}

changePassword in the User class returns true or false as an indication of its success. This fails to return a boolean. If I amend changePassword from return false to return(0) - and from return true to return(1) - it all "works". Throwing some debug code reveals nothing of note to me except to say everything else is working as I was hoping, just the return wasn't returning a boolean value (I cannot remember if it returned null or space, I'm away from my dev box at the moment).

I cannot believe this might be a reason, but I was tempted to wonder if this was down to me having User as a singleton with the constructer made private?

coopster

2:17 pm on Apr 4, 2006 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



No, I think you have something else amiss as a sample singleton function works fine for me on PHP5:
<pre> 
<?php
class User
{
private static $instance;
private function __construct()
{
}
public static function instance()
{
if (!isset(self::$instance)) {
$class = __CLASS__;
self::$instance = new $class;
}
return self::$instance;
}
public function changePassword($p = false)
{
return ($p)? true : false;
}
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
$user = User::instance();
$password = false; // toggle this value to see the var_dump boolean returned
if ( $user->changePassword($password) ) {
print "TRUE\n";
} else {
print "FALSE\n";
}
var_dump($user->changePassword($password));
exit;
?>
</pre>