@jonathanbell/

Passing type-hinted objects in PHP

PHP CLI

No description

fork
loading
Files
  • main.php
main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

class Person {

  // Only the Person needs to know their own name.
  protected $name;

  public function __construct($name) {
    $this->name = $name;
  }

}

class Staff {

  // Only the staff needs to know its own members.
  protected $members = [];

  public function __construct($members = []) {
    $this->members = $members;
  }

  public function add(Person $person) {
    $this->members[] = $person;
  }

  public function members() {
    return $this->members;
  }

}

class Business {

  protected $staff;

  public function __construct(Staff $staff) {
    $this->staff = $staff;
  }

  public function hire(Person $person) {
    $this->staff->add($person);
  }

  public function getStaffMembers() {
    return $this->staff->members();
  }

}

// Instaniate a new person, and give them a name.
$jonathan = new Person('Jonathan Bell');
// Add another person just for fun.
$fred = new Person('Fred Flintstone');

// Instantiate a new staff object and give the staff staff members.
$staff = new Staff([$jonathan, $fred]);

// Instantiate a new business and give it staff.
$business = new Business($staff);

// Hire another staff member.
// This will message the new person back to the `$staff->add()` method 
// and will add them to the `$members` array.
$business->hire(new Person('Jane Doe'));

echo 'Staff object:'.PHP_EOL;
print_r($staff);
echo 'Staff members:'.PHP_EOL;
print_r($business->getStaffMembers());