Interfaces are nominal
Lesson 36 of 48 in Coddy's PHP for Rust Developers course.
Rust trait implementations declare behavioral contracts, with generics or dyn trait objects choosing dispatch. PHP interfaces require explicit implements and compatible public methods. Matching method names alone does not establish nominal membership, and PHP has different generic and lifetime capabilities.
An interface names a contract. A class must explicitly declare implements; merely having methods with matching names does not make it an instance of that interface. A class may implement multiple interfaces. Interfaces describe public behavior, while implementation and state live in classes. Test a consumer with an independent implementation.
Rust program
trait Channel{fn send(&self,text:&str)->String;}
struct Email; impl Channel for Email{fn send(&self,text:&str)->String{format!("email:{}",text)}}
struct Sms; impl Channel for Sms{fn send(&self,text:&str)->String{format!("sms:{}",text)}}
fn main() {
let email=Email; let sms=Sms; let channels:[&dyn Channel;2]=[&email,&sms]; let out:Vec<_>=channels.iter().map(|c|c.send("hi")).collect(); println!("{}",out.join("|"));
}
Source output:
email:hi|sms:hiPHP program
Named.php
<?php
declare(strict_types=1);
interface Named {public function name():string;}
Book.php
<?php
declare(strict_types=1);
require_once __DIR__."/Named.php";class Book implements Named {public function name():string{return "atlas";}}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/Book.php";$b=new Book();echo ($b instanceof Named?"yes":"no"),"\n";
PHP output:
yesChallenge
EasyInput is integer cents. Fee defines apply(int $cents):int. FlatFee(int $amount) implements Fee; apply adds the amount. Driver uses a fee of three; values are nonnegative.
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 Fee.php, FlatFee.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__."/Fee.php";
require_once __DIR__."/FlatFee.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);
$f=new FlatFee(8);ensure($f instanceof Fee && $f->apply(4)===12,"nominal fee");
echo (string)(new FlatFee(3))->apply($input),"\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for Rust 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