Skip to content

Instantly share code, notes, and snippets.

@sagittaracc
Last active November 9, 2022 13:46
Show Gist options
  • Save sagittaracc/5c7fc4029a2103bf175fa0c9eb0c413c to your computer and use it in GitHub Desktop.
Save sagittaracc/5c7fc4029a2103bf175fa0c9eb0c413c to your computer and use it in GitHub Desktop.
Chat
<?php
$vova = new Man();
$vova->setName('Vova');
$vika = new Woman();
$vika->setName('Vika');
$petr = new Man();
$petr->setName('Petr');
$alex = new Man();
$alex->setName('Alex');
$vova->learn(new Russian());
$vika->learn(new English());
$petr->learn(new English());
$alex->learn(new Russian());
$chat = new Chat();
$chat->add($vova);
$chat->add($vika);
$chat->add($petr);
// $chat->add($alex);
$vova->says('greetings');
interface Speaking
{
public function greetings();
}
class English implements Speaking
{
public function greetings()
{
return 'Hello';
}
}
class Russian implements Speaking
{
public function greetings()
{
return 'Привет';
}
}
abstract class Human
{
private $name;
private $language;
public $chat;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function learn(Speaking $language)
{
$this->language = $language;
}
public function getLanguage()
{
return $this->language;
}
public function says($phrase)
{
$people = [];
foreach ($this->chat->getPeople() as $person) {
if ($this->name === $person->getName()) continue;
if (get_class($this->language) !== get_class($person->getLanguage())) continue;
$people[] = $person->getName();
}
if (empty($people)) {
echo 'Nobody understands';
}
else {
$people = implode(', ', $people);
echo "$this->name says {$this->language->$phrase()} to ($people)";
}
}
}
class Man extends Human
{
}
class Woman extends Human
{
}
class Chat
{
private $people = [];
public function add(Human $person)
{
$this->people[] = $person;
$person->chat = $this;
}
public function getPeople()
{
return $this->people;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment