Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Object model and composition

Composition stores one object inside another and delegates a part of its behavior.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

public function __construct(private Counter $counter) {}

Composition stores one object inside another and delegates a part of its behavior. Supplying the same collaborator to two objects shares its mutable state. Cloning the outer object by itself performs a shallow copy, so the nested collaborator stays shared unless explicitly cloned.

class Counter{private int $n=0;public function advance():int{return ++$this->n;}public function value():int{return $this->n;}} class Ticket{function __construct(private Counter $c){}function next():int{return $this->c->advance();}}
$c=new Counter();$a=new Ticket($c);$b=clone $a;echo json_encode([$a->next(),$b->next(),$c->value()]);
[1,2,2]

Examples

<?php
class Counter{private int $n=0;public function advance():int{return ++$this->n;}public function value():int{return $this->n;}} class Ticket{function __construct(private Counter $c){}function next():int{return $this->c->advance();}}
$c=new Counter();$a=new Ticket($c);$b=clone $a;echo json_encode([$a->next(),$b->next(),$c->value()]);

Result

[1,2,2]

Sources