Skip to content

Instantly share code, notes, and snippets.

@mdwheele
Last active Dec 29, 2015
Embed
What would you like to do?
Initial implementation of `friend` in PHP
<?php
class Person
{
friend SomeFriend;
protected $name;
private $age;
public function __construct() {
$this->name = 'Alice';
$this->age = 24;
}
}
class SomeFriend
{
public function guessName(Person $person)
{
// SomeFriend will have access to Person protected and
// private attributes because it is a friend of Person
echo "SomeFriend: This person's name is {$person->name}. She is {$person->age} years old." . PHP_EOL;
}
}
class Another
{
public function guessName(Person $person)
{
// Another will not have access to Person protected and
// private attributes
echo "Another: This person's name is {$person->name}. She is {$person->age} years old." . PHP_EOL;
}
}
$person = new Person();
$friend = new SomeFriend();
$another = new Another();
$friend->guessName($person);
$another->guessName($person);
SomeFriend: This person's name is Alice. She is 24 years old.
Fatal error: Uncaught Error: Cannot access protected property Person::$name in /home/vagrant/sample.php:25
Stack trace:
#0 /home/vagrant/sample.php(34): Another->guessName(Object(Person))
#1 {main}
thrown in /home/vagrant/sample.php on line 25
@TRPB

This comment has been minimized.

Copy link

@TRPB TRPB commented Dec 29, 2015

I'm not sure how to comment on an RFC but this implementation is a good idea.. although I'd make it protected only. Allowing access to both private and protected seems overkill. By only allowing protected you then have more control over what can be accessed. private means private and protected means that other, known classes can access the property/function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment