fork download
  1. <?php
  2.  
  3. class Organisation {
  4.  
  5. private $name;
  6. private $departments = [];
  7.  
  8. public function __construct($name) {
  9. $this->name = $name;
  10. }
  11.  
  12. public function addDepartment(Department $dep) {
  13. if (!in_array($dep, $this->departments)) {
  14. $this->departments[] = $dep;
  15. }
  16. else {
  17. throw new Exception('Organisation already have that department');
  18. }
  19. }
  20.  
  21.  
  22. }
  23.  
  24. class Department {
  25. public function __construct($name) {
  26. $this->name = $name;
  27. }
  28. }
  29.  
  30. $vector = new Organisation('Вектор');
  31.  
  32. $dep1 = new Department('dep1');
  33. $vector->addDepartment($dep1);
  34. $vector->addDepartment($dep1);
  35. $dep2 = new Department('dep2');
  36. $vector->addDepartment($dep2);
  37.  
  38.  
  39. var_dump($vector);
  40.  
  41.  
Runtime error #stdin #stdout #stderr 0.01s 52488KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
PHP Fatal error:  Uncaught exception 'Exception' with message 'Organisation already have that department' in /home/WlTROL/prog.php:17
Stack trace:
#0 /home/WlTROL/prog.php(34): Organisation->addDepartment(Object(Department))
#1 {main}
  thrown in /home/WlTROL/prog.php on line 17