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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.