What is the output of this PHP code?
<?php class Animal { public function sound() { return "Some sound"; } } class Dog extends Animal { public function sound() { return "Bark"; } } $dog = new Dog(); echo $dog->sound(); ?>
Remember, when a child class defines a method with the same name as the parent, it overrides it.
The Dog class extends Animal and overrides the sound() method. So calling sound() on a Dog object returns "Bark".
What will this PHP code output?
<?php class Vehicle { public function start() { return "Vehicle started"; } } class Car extends Vehicle { public function start() { return parent::start() . " and car is ready"; } } $car = new Car(); echo $car->start(); ?>
Look at how parent::start() is used inside the child method.
The Car class calls the parent start() method and appends additional text. So the output is "Vehicle started and car is ready".
What is the output of this PHP code?
<?php class Fruit { private function taste() { return "Sweet"; } } class Apple extends Fruit { public function taste() { return "Sour"; } } $apple = new Apple(); echo $apple->taste(); ?>
Private methods are not inherited or overridable; child can define its own method with the same name.
The taste() method in Fruit is private and not inherited. Apple defines its own independent taste() method, which is called and outputs "Sour". No error occurs.
Which of the following PHP code snippets will cause a syntax error?
Check how the parent method is called inside the child method.
In PHP, to call a parent method, you must use parent::methodName(). Using parent.methodName() causes a syntax error.
Given the following PHP classes, how many methods can be called on an instance of Smartphone?
<?php class Device { public function powerOn() { return "Powering on"; } protected function reset() { return "Resetting"; } private function secret() { return "Secret"; } } class Phone extends Device { public function call() { return "Calling"; } protected function reset() { return "Phone reset"; } } class Smartphone extends Phone { public function browse() { return "Browsing"; } private function secret() { return "Smartphone secret"; } } $phone = new Smartphone();
Count the public methods that can be called directly on a Smartphone instance from outside: powerOn(), call(), browse().
Public methods callable on a Smartphone instance from outside:
- powerOn() (from Device)
- call() (from Phone)
- browse() (from Smartphone)
Protected reset() cannot be called from outside. Private methods are inaccessible. Total: 3.