php 在下面的代码中,我想最后运行honk()方法,但在输出中,honk()方法首先运行,为什么

vlurs2pr  于 5个月前  发布在  PHP
关注(0)|答案(2)|浏览(48)
<?php 
        class Vehicle{
            protected $brand;

            function __construct($brand){
                $this->setBrand($brand);
            }
            function setBrand($brand){
                $this->brand=$brand;
            }

            function getBrand(){
                return $this->brand;
            }

            function honk(){
                echo "Beep Beep Beep...";
            }
        }

        class Car extends Vehicle{
            private $modelName;

            function setModelName($modelName){
                $this->modelName=$modelName;
            }

            function getModelName(){
                return $this->modelName;
            }
        }

        $carObject = new Car("Lamborghini");
        echo "</br>Car brand is ".$carObject->getBrand()."<br>";
        $carObject->setModelName("Aventador");
        echo "Car model is ".$carObject->getModelName()."<br>";

        echo($carObject->getBrand()." ".$carObject->getModelName()." is ".$carObject->honk());

    ?>

字符串
我把这个函数添加到子类中。但是我也不理解那个函数。

function honk(){
    parent::honk();
}


我想要的输出是:兰博基尼Aventador是哔......但我得到哔......兰博基尼Aventador是

hi3rlvi2

hi3rlvi21#

在这一行:

echo($carObject->getBrand()." ".$carObject->getModelName()." is ".$carObject->honk());

字符串
方法调用在以下情况下进行评估:
1.调用$carObject->getBrand()返回字符串Lamborghini
1.调用$carObject->getModelName()返回字符串Aventador

  1. $carObject->honk()被调用,回显字符串Beep Beep Beep...到输出。它不返回任何东西。
    1.前面步骤中的所有字符串都被插入并回显到输出:
echo('Lamborghini'." ".'Aventador'." is ".'');

因此导致Beep Beep Beep...Lamborghini Aventador is
您可能想在honk()中使用return

function honk(){
  return "Beep Beep Beep...";
}

knsnq2tg

knsnq2tg2#

function honk(){
  echo "Beep Beep Beep...";
}

字符串
你的honk echo首先运行,然后最后一个echo运行。也许你需要return而不是echo来发送消息?

相关问题