Skip to content

Instantly share code, notes, and snippets.

@mpessolano
Last active December 3, 2021 18:38
Show Gist options
  • Select an option

  • Save mpessolano/5ef2c274c5b951b9961de23cf3b82822 to your computer and use it in GitHub Desktop.

Select an option

Save mpessolano/5ef2c274c5b951b9961de23cf3b82822 to your computer and use it in GitHub Desktop.
Lección 2: Encapsulamiento, getters y setters en PHP
<?php
class Person
{
protected $firstName; // public, protected <-> private
protected $lastName;
protected $nickname;
protected $changedNickname = 0;
public function __construct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
// public function setFirstName($firstName)
// {
// $this->firstName = $firstName;
// }
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
// public function setNickname($nickname)
// {
// if (! empty($nickname)) {
// $this->nickname = $nickname;
// }
// }
// public function setNickname($nickname)
// {
// if ($this->changedNickname < 2) {
// $this->nickname = $nickname;
// $this->changedNickname++;
// }
// }
public function setNickname($nickname)
{
if ($this->changedNickname >= 2) {
throw new Exception(
"You can't change a nickname more than 2 times"
);
}
$this->nickname = $nickname;
$this->changedNickname++;
}
public function getNickname()
{
return $this->nickname;
}
public function getFullName()
{
return $this->firstName . ' ' . $this->lastName;
}
}
$person1 = new Person('Duilio', 'Palacios');
$person1->setNickname('Silence');
$person1->setNickname('Sileence');
// $person1->setNickname('duilio');
exit($person1->getNickname());
//------------------------------------------------------------------------------
// Output for PHP 7.4.14
//------------------------------------------------------------------------------
// Sileence
//------------------------------------------------------------------------------

Ejercicio propuesto:

  • Agrega validación adicional para que el usuario sólo pueda agregar nicknames que tengan al menos 2 caracteres (y sea una cadena de texto) y no sean igual a su nombre o apellido.

  • Agrega la propiedad «fecha de nacimiento» a la clase persona, y que esta propiedad pueda pasarse a través del constructor. Luego crea un método para obtener la edad del usuario (getAge), por supuesto la edad la vas a calcular a partir de la fecha de nacimiento.

<?php
class Person
{
protected $firstName;
protected $lastName;
protected $nickname;
protected $changedNickname = 0;
private $dateOfBirth;
public function __construct($firstName, $lastName, $dateOfBirth)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->dateOfBirth = $this->validateDate($dateOfBirth);
}
private function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
if (!$d || $d->format($format) !== $date) {
throw new Exception(
'Invalid date'
);
}
return $date;
}
public function getDateOfBirth()
{
return $this->dateOfBirth;
}
/**
* Calculate age using $this->dateOfBirth
*/
public function getAge()
{
$from = new DateTime($this->dateOfBirth);
$to = new DateTime('today');
$age = $from->diff($to)->y;
return $age;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
public function setNickname($nickname)
{
if ($this->changedNickname >= 2) {
throw new Exception(
"You can't change a nickname more than 2 times"
);
}
if (strlen($nickname) < 2 || !is_string($nickname)) {
throw new Exception(
'Nickname must be at least 2 characters long and be a string'
);
}
if ($nickname==$this->firstName || $nickname==$this->lastName) {
throw new Exception(
'Nickname must be different from first and last name'
);
}
$this->nickname = $nickname;
$this->changedNickname++;
}
public function getNickname()
{
return $this->nickname;
}
public function getFullName()
{
return $this->firstName . ' ' . $this->lastName;
}
}
$person1 = new Person('John', 'Doe', '1980-12-01');
// $person1->setNickname('j');
// $person1->setNickname(12);
// $person1->setNickname('John');
// $person1->setNickname('Doe');
$person1->setNickname('JD');
$nl = strpos(PHP_SAPI, 'apache') !== FALSE ? '<br>' : chr(10);
echo $person1->getNickname() . $nl . $person1->getAge();
//------------------------------------------------------------------------------
// Output for PHP 7.4.14
//------------------------------------------------------------------------------
// JD
// 40
//------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment