I have written the following function to concatenate the parts of a name to produce the full name:
/**
* Returns the full name of the Person.
* @param boolean $includeTitle Whether to include the Person's title.
* @param boolean $includeMiddleNames Whether to include the Person's middle names.
* @param string $separator Separator character.
* @return string Full name of the Person.
*/
public function getFullName($includeTitle = false, $includeMiddleNames = false, $separator = ' ') {
if ($includeTitle && $this->getTitle()) {
$name = $this->title;
} else {
$name = '';
}
if ($this->forename) {
if ($name) {
$name .= $separator;
}
$name .= $this->forename;
}
if ($includeMiddleNames && $this->middlenames) {
if ($name) {
$name .= $separator;
}
if ($separator != ' ') {
// multiple middle names will be separated by spaces and so will need to be converted to $separator
$name .= str_replace(' ', $separator, $this->middlenames);
} else {
$name .= $this->middlenames;
}
}
if ($this->surname) {
if ($name) {
$name .= $separator;
}
$name .= $this->surname;
}
return $name;
}
I changed it to use an array and implode the parts - which has made it less lines, but I'm not really sure if it is written better as a result:
$nameParts = array();
if ($includeTitle && $this->getTitle()) {
$nameParts[] = $this->title;
}
if ($this->forename) {
$nameParts[] = $this->forename;
}
if ($includeMiddleNames && $this->middlenames) {
if ($separator != ' ') {
$middlenames = str_replace(' ', $separator, $this->middlenames);
} else {
$middlenames = $this->middlenames;
}
$nameParts[] = $middlenames;
}
if ($this->surname) {
$nameParts[] = $this->surname;
}
return implode($separator, $nameParts);
I'm sure there must also be a better way but I can't think what. Any suggestions?