Skip to content

Instantly share code, notes, and snippets.

@LordZardeck
Last active February 13, 2018 19:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LordZardeck/cf71a0911c601966c728715d96eeb749 to your computer and use it in GitHub Desktop.
Save LordZardeck/cf71a0911c601966c728715d96eeb749 to your computer and use it in GitHub Desktop.
Crazy feature I discovered in PHP. You can access protected properties of a instance if the method that's accessing those protected propteries exist on the same type of that instance, even if it's not the instance you are accessing from. Seems similar to C# nested types: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-an…

HasProtectedProperty

string(6) "foobar"

HasPrivateProperty

string(6) "barfoo"
<?php
class HasProtectedProperty {
protected $myProtectedProperty;
public function __construct()
{
$this->myProtectedProperty = 'foobar';
}
public function getProtectedProperty(HasProtectedProperty $hasProtectedProperty)
{
return $hasProtectedProperty->myProtectedProperty;
}
}
$newProtectedProperty = new HasProtectedProperty();
$readProtectedProperty = new HasProtectedProperty();
var_dump($readProtectedProperty->getProtectedProperty($newProtectedProperty));
class HasPrivateProperty {
private $myPrivateProperty;
public function __construct()
{
$this->myPrivateProperty = 'barfoo';
}
public function getPrivateProperty(HasPrivateProperty $hasPrivateProperty)
{
return $hasPrivateProperty->myPrivateProperty;
}
}
$newPrivateProperty = new HasPrivateProperty();
$readPrivateProperty = new HasPrivateProperty();
var_dump($readPrivateProperty->getPrivateProperty($newPrivateProperty));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment