Skip to content

Instantly share code, notes, and snippets.

@flowl
Created June 28, 2018 13:33
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 flowl/774c6e6335b6cb205c352ad67af2799c to your computer and use it in GitHub Desktop.
Save flowl/774c6e6335b6cb205c352ad67af2799c to your computer and use it in GitHub Desktop.
Accessing a different's instance protected members in PHP
<?php
abstract class A {
abstract protected function test();
}
class Api extends A {
protected function test() { echo 'aaa ', __CLASS__, PHP_EOL; }
}
class Cache extends A {
private $api;
public function __construct(A $api)
{
$this->api = $api;
}
protected function test() { echo 'bbb ', __CLASS__, PHP_EOL; }
public function foo()
{
$this->api->test();
}
public function bar()
{
$this->test();
}
}
$cache = new Cache(new Api());
$cache->foo(); // aaa Api
$cache->bar(); // bbb Cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment