ThePickyGuy ThePickyGuy - 4 months ago 10
PHP Question

Multiple if Statements within a function in an Object?

Hi i need to check if an Object can have 0 or 1 for two parameters which are R1 and R2 - it's like directions from Obj A to Obj B - Where 1 means Obj A can access Obj B and 0 means Obj A cannot access Obj B. My if statements work until the first true statement. How to make them check both R1 and R2 directions

<?php

class MyObject {

function directionsRn($R1, $R2, $objSource, $objDest) {


if ($R1 == 1) {

echo("$objSource can access $objDest via R1 <br>");

} else if ($R1 == 0) {

echo("SORRY, but $objSource CANNOT access $objDest via R1 <br>");

} else if ($R2 == 1) {

echo("$objSource can access $objDest via R12<br>");

} else if ($R2 == 0) {

echo("SORRY, but $objSource CANNOT access $objDest via R1 <br>");

}

}

}

$myObject_array[0] = new MyObject();

$myObject_array[0]->directionsRn(0, 0, 'A', 'B');

print_r($myObject_array);



?>

Answer

Fix it by changing from

} else if ($R2 == 1) {

to

}

if ($R2 == 1) {

If you properly ident your code, it would look like this:

if ($R1 == 1) {
    echo("$objSource can access $objDest via R1 <br>");
} else if ($R1 == 0) {
    echo("SORRY, but $objSource CANNOT access $objDest via R1 <br>");
} else if ($R2 == 1) {
    echo("$objSource can access $objDest via R12<br>");
} else if ($R2 == 0) {
    echo("SORRY, but $objSource CANNOT access $objDest via R1 <br>");
}

Can you see that it's all part of one if?


They'd look like this separated (note that I changed to elseif too):

if ($R1 == 1) {
    echo("$objSource can access $objDest via R1 <br>");
} elseif ($R1 == 0) {
    echo("SORRY, but $objSource CANNOT access $objDest via R1 <br>");
}

if ($R2 == 1) {
    echo("$objSource can access $objDest via R12<br>");
} elseif ($R2 == 0) {
    echo("SORRY, but $objSource CANNOT access $objDest via R1 <br>");
}