-
-
Save mdwheele/6d9b178dc25ebb829e4c to your computer and use it in GitHub Desktop.
Initial implementation of `friend` in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 allowingprotected
you then have more control over what can be accessed.private
meansprivate
andprotected
means that other, known classes can access the property/function.