Rubyのprivate methodはサブクラスからも呼び出せる
PHPとRubyのprivate methodを比較してみる
子クラスから親クラスのprivate methodが呼び出せるか、
確かめてみます。
PHPの場合
実行コード
<?php // 親クラスを定義 class Hoge { private function hello1() { echo 'hello1 from Hoge'; } } // 子クラスを定義 class HogeExtended extends Hoge { public function hello2() { parent::hello1(); } } $hogeExtended = new HogeExtended(); // 子クラスから親クラスのprivate methodを呼び出す $hogeExtended->hello2();
結果
Call to private method Hoge::hello1() from context 'HogeExtended'
呼び出せない。
Rubyの場合
実行コード
class Hoge private def pri_hello puts 'hoge_pri_hello' end end class HogeExtend < Hoge public def ex_pub_hello pri_hello # 親クラスのprivate methodを呼び出す end end hogeex = HogeExtend.new hogeex.ex_pub_hello
結果
hoge_pri_hello
呼び出せる。
まとめ
子クラスから親クラスのprivate methodを
正直ビビりました。