NoFriend.php
<?php
class Person
{
protected $id;
protected $firstName;
protected $lastName;
public function __construct($id, $firstName, $lastName)
{
$this->id = $id;
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getId()
{
return $this->id;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
}
class HumanResourceReport
{
private $person;
public function __construct(Person $person)
{
$this->person = $person;
}
public function getFullName()
{
return $this->person->getFirstName() . ' ' . $this->person->getLastName();
}
public function getReportIdentifier()
{
return "HR_REPORT_ID_{$this->person->getId()}";
}
}
$person = new Person('uniq_id', 'Alice', 'Wonderland');
$report = new HumanResourceReport($person);
var_dump($report->getFullName()); // string(16) "Alice Wonderland"
var_dump($report->getReportIdentifier()); // string(49) "HR_REPORT_ID_uniq_id"
<?php
class Person
{
protected $id;
protected $firstName;
protected $lastName;
public function __construct($id, $firstName, $lastName)
{
$this->id = $id;
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function mustBeGranted()
{
$trace = debug_backtrace();
if (isset($trace[2]['class']) && HumanResourceReport::class === $trace[2]['class']) {
return true;
}
throw new \Exception("The caller class is not allowed to do this.");
}
public function getId()
{
$this->mustBeGranted();
return $this->id;
}
public function getFirstName()
{
$this->mustBeGranted();
return $this->firstName;
}
public function getLastName()
{
$this->mustBeGranted();
return $this->lastName;
}
}
class HumanResourceReport
{
private $person;
public function __construct(Person $person)
{
$this->person = $person;
}
public function getFullName()
{
return $this->person->getFirstName() . ' ' . $this->person->getLastName();
}
public function getReportIdentifier()
{
return "HR_REPORT_ID_{$this->person->getId()}";
}
}
$person = new Person('uniq_id', 'Alice', 'Wonderland');
$report = new HumanResourceReport($person);
var_dump($report->getFullName()); // string(16) "Alice Wonderland"
var_dump($report->getReportIdentifier()); // string(49) "HR_REPORT_ID_uniq_id"
var_dump($person->getFirstName()); // PHP Fatal error: Uncaught Exception: The caller class is not allowed to do this.