プロパティの可視性について調べたので、次はメソッドについて。

メソッドの可視性について

<?php
class MethodVisiblity
{
private $name = "parent";
public function __construct()
{
$this->privateFunction($this->name);
$this->protectedFunction($this->name);
$this->publicFunction($this->name);
}
private function privateFunction($at)
{
echo $this->name." : privateFunction @ : ".$at."\n";
}
protected function protectedFunction($at)
{
echo $this->name." : protectedFunction @ : ".$at."\n";
}
public function publicFunction($at)
{
echo $this->name." : publicFunction @ : ".$at."\n";
}
}
class Extension extends MethodVisiblity
{
private $name = "child";
public function __construct()
{
//$this->privateFunction($this->name); //Fatal error: Call to private method MethodVisiblity::privateFunction() from context 'Extension'
$this->protectedFunction($this->name);
$this->publicFunction($this->name);
}
}
$var = new MethodVisiblity();
$child = new Extension();

実行結果はこうなった。

実行結果
parent : privateFunction @ : parent
parent : protectedFunction @ : parent
parent : publicFunction @ : parent
parent : protectedFunction @ : child //親のメソッドが子で実行されるので、こうなる。
parent : publicFunction @ : child