Jump to content

PHP OOP static with Boolean?


Muck A. Round
 Share

Recommended Posts

I am missing something with this code I decided to try.  See comment in code for problem converting 0 or 1 to TRUE or FALSE ?

<?php
$x = 11;
var_dump ($x & 1);
echo "<br>";
//
// var_dump is showing int(0) or int(1) for even or odd but function below is always saying even???
//
class calculations {
  public static function OddorEven() {
    if ($x & 1) {
     echo "x is odd";}
     else {
     echo "x is even";}
  }
}
// Call static method
calculations::OddorEven();
?>

Link to comment
Share on other sites

Variables are not global in PHP, so your function does not have access to $x. Because of that, $x is undefined, which is equivalent to 0.

You should pass the variable into the function if you want to use it, like this:

<?php
$x = 11;
var_dump ($x & 1);
echo "<br>";
//
// var_dump is showing int(0) or int(1) for even or odd but function below is always saying even???
//
class calculations {
  public static function OddorEven($value) {
    if ($value & 1) {
     echo "x is odd";}
     else {
     echo "x is even";}
  }
}
// Call static method
calculations::OddorEven($x);
?> 

 

  • Thanks 1
Link to comment
Share on other sites

18 hours ago, Ingolme said:

Variables are not global in PHP, so your function does not have access to $x. Because of that, $x is undefined, which is equivalent to 0.

You should pass the variable into the function if you want to use it, like this:

<?php
$x = 11;
var_dump ($x & 1);
echo "<br>";
//
// var_dump is showing int(0) or int(1) for even or odd but function below is always saying even???
//
class calculations {
  public static function OddorEven($value) {
    if ($value & 1) {
     echo "x is odd";}
     else {
     echo "x is even";}
  }
}
// Call static method
calculations::OddorEven($x);
?> 

 

Ah Thank you !!  Wait... that still doesn't work.  I have to declare $x as global or something.

Edited by Muck A. Round
tried code; didn't work
Link to comment
Share on other sites

I've tested the code I wrote and it is correctly distinguishing odd and even values of $x. If you've changed the code then I'll have to see what changes you made to find out why it's not working.

Link to comment
Share on other sites

4 hours ago, Ingolme said:

I've tested the code I wrote and it is correctly distinguishing odd and even values of $x. If you've changed the code then I'll have to see what changes you made to find out why it's not working.

Ah - I didn't make all the changes - putting $value in the static function and if/else.  I had only added $x to the call.   Thanks !!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...