麥克乙方在評論你應該先說將您的TeamMember實例分組到一個Team類的實例中,然後運行一些聚合函數來計算該特定團隊的總分數,例如
<?php
$team1 = Team::create('Team 1')
->add(TeamMember::create('john')->SetScore(182))
->add(TeamMember::create('paul')->SetScore(212));
$team2 = Team::create('Team 2')
->add(TeamMember::create('peter')->SetScore(200))
->add(TeamMember::create('marry')->SetScore(300));
foo($team1);
foo($team2);
function foo(Team $team) {
$score = $team->membersReduce(
function($v, $e) {
return $v+$e->getScore();
}
);
$members = $team->membersMap(
function($e) {
return $e->getName();
}
);
echo 'team : ', $team->getName(), "\r\n";
echo 'score: ', $score, "\r\n";
echo 'members: ', join(' | ', $members), "\r\n";
}
class TeamMember {
protected $score = 0;
protected $name;
public static function create($name) {
return new TeamMember($name);
}
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function SetScore($value) {
$this->score = $value;
return $this;
}
public function GetScore() {
return $this->score;
}
}
class Team {
protected $members = array();
protected $name;
public static function create($name) {
return new Team($name);
}
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function add(TeamMember $t) {
// <-- check if $t already member of team -->
$this->members[] = $t;
return $this;
}
public function membersReduce($fn) {
return array_reduce($this->members, $fn);
}
public function membersMap($fn) {
return array_map($fn, $this->members);
}
}
打印
team : Team 1
score: 394
members: john | paul
team : Team 2
score: 500
members: peter | marry
首先你的類需要訪問的所有對象。因此,您需要將它傳遞給GetTotalScoreForTeam()或將其設置爲屬性。約翰的182分不知道保羅是否存在,或者他得到了212分。組織方面......我不知道爲什麼一名隊員會有一種方法來計算球隊的得分。這應該在Team類中的某個地方保存所有TeamMember對象。 –