0

I've just started working with OOP in PHP. I'm creating an instance with a boolean value and running an if statement in a Class method. When running the true boolean value does not run the if statement. However when I run the same type of if statement outside of a class method it does work as expected. Why? Thanks for any clarifications, here's the code.

  <?php 
    class Knowledge {
        public $youKnow; 
        public function __construct($youKnow) {
            $this->youKnow = $youKnow;
            echo $youKnow;  /*   "1"    */
            echo "\n";
        }
        public function yesOr() {
            if ($youKnow) {
                echo "Now I know the basics of OOP!";
            } else { echo "not"; }
            /*  "not"    is echoed...   */
        }
    }    

    $randInstance = new Knowledge(true);

    $randInstance->yesOr();


    $try = true;
    if($try){
        echo $try;  /*   "1"    */
        echo "this one works!"; /*  "this one works!    */
    }

  ?>

Also how do I get the bool to return True (False) and not "1"?

DrSocket
  • 135
  • 1
  • 11

2 Answers2

0

Ok I just figured something out, if I change the class method's boolean variable to $this->youKnow, the if statement works as expected.

        public function yesOr() {
            if ($this->youKnow) {
                echo "Now I know the basics of OOP!";
            } else { echo "not"; }
            /*  "Now I know the basics of OOP!"  is echoed...   */
        }

I'm still curious to know why true becomes "1". I'd also like to know why the variable $youKnow cannot be used as equivalent to $this->youKnow once it's been assigned.

DrSocket
  • 135
  • 1
  • 11
  • PHP casts variable to string before printing one and string value for boolean is "1" or "0". see this answer https://stackoverflow.com/questions/4948663/php-get-bool-to-echo-false-when-false – akaincore Jan 27 '18 at 10:30
  • such a strange functionality of PHP to change datatype once you have created it. Thank's for the thread. – DrSocket Jan 27 '18 at 10:34
0
class Knowledge {

    public $youKnow;

    public function __construct($youKnow) {
        $this->youKnow = $youKnow;
        echo $youKnow;  /*   "1"    */
        echo "\n";
    }

    public function yesOr() {
        if ($this->youKnow == true) {
            echo "Now I know the basics of OOP!";
        } else {
            echo "not";
        }
        /*  "not"    is echoed...   */
    }

}

$randInstance = new Knowledge(true);
$randInstance->yesOr();
SAR
  • 1,765
  • 3
  • 18
  • 42
  • ok, thank you, but what was the point of assigning the boolean value true to the constructor if we have to pass it again once the method is called? – DrSocket Jan 27 '18 at 10:30
  • well that's pretty much the solution I came up with, although the "== true)" in the if statement is unnecessary. Do you know why it treats the variables $this->youKnow differently as youKnow. in the if statement? – DrSocket Jan 27 '18 at 10:36