Skip to content

Instantly share code, notes, and snippets.

@mdwheele
Created August 11, 2014 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwheele/6759a6c381f82abdf06f to your computer and use it in GitHub Desktop.
Save mdwheele/6759a6c381f82abdf06f to your computer and use it in GitHub Desktop.
An example of how one might implement a pseudo-friend relationship between two PHP objects.
<?php
class SampleEntity
{
private $friend = 'SampleEntityPresenter';
protected $firstName;
protected $lastName;
public function __construct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function __get($property)
{
if ($this->friend !== $this->getCallingClass()) {
throw new Exception("SampleEntity can only be accessed by SampleEntityPresenter.");
}
return $this->$property;
}
private function getCallingClass()
{
$backtrace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
$backtrace = end($backtrace);
return $backtrace['class'];
}
}
class SampleEntityPresenter
{
private $entity;
public function __construct(SampleEntity $entity)
{
$this->entity = $entity;
}
public function getFullName()
{
return $this->entity->firstName . ' ' . $this->entity->lastName;
}
}
// Sample code.
$entity = new SampleEntity('Dustin', 'Wheeler');
$presenter = new SampleEntityPresenter($entity);
// Access through presenter succeeds.
echo $presenter->getFullName() . PHP_EOL;
// Direct-access fails with Exception.
echo $entity->firstName . ' ' . $entity->lastName . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment