Inheritance and overriding
Lesson 35 of 48 in Coddy's PHP for C Developers course.
C can embed a base struct and delegate to helper functions, but it has no class inheritance or automatic virtual dispatch. PHP extends provides a single parent class with overriding rules. Call parent behavior deliberately and use composition for replaceable collaborators.
A class extends at most one parent class. An overriding method must respect compatible visibility and types. parent::method calls parent implementation; merely overriding does not invoke it. Prefer inheritance for a real substitutable relationship and composition for replaceable collaborators. final blocks further extension or overriding where declared.
C program
#include <stdio.h>
struct Base { int price; };
struct Child { struct Base base; int fee; };
static int base_total(const struct Base *self, int quantity)
{
return self->price * quantity;
}
static int child_total(const struct Child *self, int quantity)
{
return base_total(&self->base, quantity) + self->fee;
}
int main(void)
{
struct Child child = {{3}, 2};
printf("%d\n", child_total(&child, 4));
return 0;
}Source output:
14PHP program
Message.php
<?php
declare(strict_types=1);
class Message {public function text():string{return "base";}}
LoudMessage.php
<?php
declare(strict_types=1);
require_once __DIR__."/Message.php";class LoudMessage extends Message {public function text():string{return strtoupper(parent::text());}}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/LoudMessage.php";echo (new LoudMessage())->text(),"\n";
PHP output:
BASEChallenge
EasyInput is [base,extra], nonnegative integer points. Score(base) points():int returns base. BonusScore(base,extra) extends Score, initializes parent and overrides points to add extra. Keep base usable independently.
The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.
Edit Score.php, BonusScore.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.
Try it yourself
<?php
declare(strict_types=1);
require_once __DIR__."/Score.php";
require_once __DIR__."/BonusScore.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure((new Score(2))->points()===2,"base");$s=new BonusScore(4,3);ensure($s instanceof Score && $s->points()===7,"override");
echo (string)(new BonusScore(...$input))->points(),"\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for C Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents7Object contracts
Visibility and invariantsStatic methods and factoriesInheritance and overridingInterfaces are nominalComposition and injectionRecap: selectable policy2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batchPractice on your own: Online PHP compiler