Skip to content

Instantly share code, notes, and snippets.

@cr0wst
Created February 24, 2018 19:44
Show Gist options
  • Save cr0wst/9ad776bfe122312fab1a79585fc9e669 to your computer and use it in GitHub Desktop.
Save cr0wst/9ad776bfe122312fab1a79585fc9e669 to your computer and use it in GitHub Desktop.
Example of Person w/ Builder.
<?php
class Person {
protected $firstName;
protected $middleName;
protected $lastName;
protected $age;
protected $gender;
protected $height;
public static function Builder()
{
return new class extends Person {
public function build()
{
$person = new Person;
foreach (get_object_vars($this) as $key => $value) {
$person->{$key} = $this->{$key};
}
return $person;
}
public function setFirstName($firstName)
{
$this->firstName = $firstName;
return $this;
}
public function setMiddleName($middleName)
{
$this->middleName = $middleName;
return $this;
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
public function setAge($age)
{
$this->age = $age;
return $this;
}
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
public function setHeight($height)
{
$this->height = $height;
return $this;
}
};
}
public function getFirstName()
{
return $this->firstName;
}
public function getMiddleName()
{
return $this->middleName;
}
public function getLastName()
{
return $this->lastName;
}
public function getAge()
{
return $this->age;
}
public function getGender()
{
return $this->gender;
}
public function getHeight()
{
return $this->height;
}
}
$person = Person::Builder()->setFirstName('Steve')->setLastName('Crow')->build();
echo "Hello {$person->getFirstName()} {$person->getLastName()}!";
// Can't change the name
$person->setFirstName("Bob");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment