LoginSignup
4
4

More than 5 years have passed since last update.

同じクラスのインスタンス同士でprivateフィールドを参照

Last updated at Posted at 2016-02-18

メモっておけばいつか使うかもしれない(使うとは言っていない)

class Person
{
    private $secret;

    public function __construct($secret)
    {
        $this->secret = $secret;
    }

    public function look(Person $person)
    {
        return $person->secret;
    }

    public static function lookStatic(Person $person)
    {
        return $person->secret;
    }
}

class Other
{
    public static function lookStatic(Person $person)
    {
        return $person->secret;
    }
}

$me      = new Person('ブログ');
$brother = new Person('日記');

echo $me->look($brother);
echo Person::lookStatic($me);
echo Other::lookStatic($brother);

結果は上から順に

日記
ブログ
Fatal error: Cannot access private property Person::$secret

staticメソッドのほうはともかく、同じクラスのインスタンス同士でも
privateフィールドにアクセスできるのは知りませんでした。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4