Complete the code to call the parent class method inside the child class.
<?php class Base { public function greet() { echo "Hello from Base\n"; } } class Child extends Base { public function greet() { [1]::greet(); } } $child = new Child(); $child->greet(); ?>
self instead of parent to call the parent method.this which refers to the current object, not the parent.In PHP, the parent keyword is used to call a method from the parent class inside a child class.
Complete the code to override the constructor and call the parent constructor.
<?php class Animal { public function __construct() { echo "Animal created\n"; } } class Dog extends Animal { public function __construct() { [1]::__construct(); echo "Dog created\n"; } } $dog = new Dog(); ?>
self::__construct() which calls the current class constructor, causing recursion.To call the parent class constructor inside the child constructor, use parent::__construct().
Fix the error in calling the parent method inside a static method.
<?php class ParentClass { public static function sayHello() { echo "Hello from Parent\n"; } } class ChildClass extends ParentClass { public static function sayHello() { [1]::sayHello(); echo "Hello from Child\n"; } } ChildClass::sayHello(); ?>
$this inside a static method causing an error.self which calls the current class method, not the parent.Inside a static method, use parent::method() to call the parent static method.
Fill both blanks to correctly call the parent method and access a parent property.
<?php class Vehicle { protected static $type = "Vehicle"; public function getType() { return $this->type; } } class Car extends Vehicle { public function getType() { echo [1]::getType(); echo " is a car."; } public function showType() { echo [2]::$type; } } $car = new Car(); $car->getType(); $car->showType(); ?>
self instead of parent to call the parent method.parent to access a non-static property causing an error.Use parent::getType() to call the parent method and Vehicle::$type to access the protected property statically.
Fill all three blanks to override a method, call the parent method, and add extra behavior.
<?php class Logger { public function log($msg) { echo "Log: $msg\n"; } } class FileLogger extends Logger { public function log($msg) { [1]::log($msg); echo [2] . " - logged to file" . [3]; } } $logger = new FileLogger(); $logger->log("Error occurred"); ?>
self instead of parent to call the parent method.$msg in the echo statement.Use parent::log($msg) to call the parent method, then echo the message variable $msg followed by a newline "\n".