我只是在用 PHP 审查 OOP,并且在让布尔值工作时遇到麻烦



我刚刚开始在PHP中使用OOP。我正在创建一个具有布尔值的实例,并在类方法中运行 if 语句。运行时,true 布尔值不会运行 if 语句。但是,当我在类方法之外运行相同类型的 if 语句时,它确实按预期工作。为什么?感谢您的任何澄清,这是代码。

  <?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!    */
    }
  ?>

另外,如何让布尔值返回真(假(而不是"1"?

好的,

我刚刚想通了一些东西,如果我将类方法的布尔变量更改为 $this->youKnow,if 语句将按预期工作。

        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...   */
        }

我仍然很好奇为什么 true 变成"1"。我还想知道为什么变量$youKnow一旦被分配就不能等同于$this->youKnow。

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();

相关内容

最新更新