Jump to content

[SOLVED] inside PHP class, variable logical operator not working? why?


dsaba

Recommended Posts

<?php
class testClass{
var $lala = 'no';

function samba() {
	if ($this->lala == 'no') {
		$temp = $this->lion();
		echo "temp is: $temp<br>";
		if ($temp == 'no') {
			echo 'this is not right';
		}
	}
}
function lion() {
	if ($this->lala == 'no') {
		return 0;
	}
}

}

$obj = new testClass();
$whatever = $obj->samba();
?>

 

 

on this line:

echo "temp is: $temp<br>";

if ($temp == 'no') {

echo 'this is not right';

}

 

it will echo out temp as '0', yet it this condition will check to be true $temp == 'no', even though temp is obviously not 'no' but really '0'... what's going on?

How can I fix it?

(to better understand you can run the code)

 

-thanks

Link to comment
Share on other sites

here's the answer:

 

when making comparisons with integers and strings, PHP will convert the string into an integer, and this converted string will always equal 0 (correct me if i'm wrong)

 

so when comparing the integer 0 to the string 'no' it is really comparing:

the integer 0 to the translated integer representation of the string (which is 0) of 'no'

 

 

this yielding the condition of 0 == 'no' to TRUE

 

 

*edit

OR I could use the === operator to check for comparison within the same type

so 'no' === 0 will evaluate as FALSE

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.