skip to Main Content
<?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());

    ?>

I added this function to subclass. but i do not understand that function too.

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

The output that i want is: Lamborghini Aventador is Beep Beep Beep…
but i am getting Beep Beep Beep…Lamborghini Aventador is

2

Answers


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

    Your honk echo runs first and then the last echo runs. Perhaps you need to return the message instead of echo?

    Login or Signup to reply.
  2. In this line:

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

    The method calls are evaluated one after:

    1. $carObject->getBrand() is called, returning the string Lamborghini.
    2. $carObject->getModelName() is called, returning the string Aventador.
    3. $carObject->honk() is called, echoing the string Beep Beep Beep... to the output. It does not return anything.
    4. All the strings in previous steps are inserted and echoed to the output:
      echo('Lamborghini'." ".'Aventador'." is ".'');
      

      Thus leading to Beep Beep Beep...Lamborghini Aventador is.

    You may have meant to return in honk():

    function honk(){
      return "Beep Beep Beep...";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search