CKTIS / PHP
Обектен модел и композиция
Композицията пази обект в друг и му делегира част от поведението.
Версия: PHP 8.4; repository runtime, production runtime not attested
Синтаксис
public function __construct(private Counter $counter) {}Композицията пази обект в друг и му делегира част от поведението. Два обекта с един и същ помощен обект споделят променливото му състояние. Обичайният clone на външния е плитък и вътрешният остава споделен до изрично клониране.
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]
Примери
<?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()]);
Резултат
[1,2,2]