可視性について、ちょっと調べてみた。

  • private
  • protected
  • public

があるらしい。C#みたいにinternalはないようだ。5.3.0から名前空間が導入されたのに。どうも名前空間の役割が違うのかもしれない。

プロパティの可視性

<?php
class Visiblity
{
public $name = "parent";
private $istr1 = "private string.\n";
protected $istr2 = "protected string.\n";
public $istr3 = "public string.\n";
private static $sstr1 = "private static string.\n";
protected static $sstr2 = "protected static string.\n";
public static $sstr3 = "public static string.\n";
//クラス内からは全部のインスタンス変数にアクセスできるはず。
public function checkInstance()
{
echo "\n";
echo $this->name." checkInstance\n";
echo $this->istr1;
echo $this->istr2;
echo $this->istr3;
}
//クラス変数も同様のはず。
public function checkStatic()
{
echo "\n";
echo $this->name." checkStatic\n";
echo self::$sstr1;
echo self::$sstr2;
echo self::$sstr3;
}
}
class Extension extends Visiblity
{
public $name = "child";
//親のprivateは見れないはず。
public function checkParent()
{
echo "\n";
echo $this->name." checkParent\n";
//echo $this->istr1; //Notice: Undefined property: Extension::$istr1
echo $this->istr2;
echo $this->istr3;
}
//親のprivateは見れないはず。
public function checkParentStatic()
{
echo "\n";
echo $this->name." checkParentStatic\n";
//echo parent::$sstr1; //Fatal error: Cannot access private property Visiblity::$sstr1
echo parent::$sstr2;
echo parent::$sstr3;
}
}
//echo Visiblity::$sstr1; //Fatal error: Cannot access private property Visiblity::$sstr1
//echo Visiblity::$sstr2; //Fatal error: Cannot access protected property Visiblity::$sstr2
echo Visiblity::$sstr3;
$var = new Visiblity();
//echo $var->istr1; //Fatal error: Cannot access private property PropertyVisiblity::$istr1
//echo $var->istr2; //Fatal error: Cannot access protected property PropertyVisiblity::$istr2
echo $var->istr3; //public string.
$var->checkInstance();
$var->checkStatic();
$child = new Extension();
$child->checkInstance();
$child->checkStatic();
$child->checkParent();
$child->checkParentStatic();

実行結果はこうなった。

実行結果
public static string.
public string.
parent checkInstance
private string.
protected string.
public string.
parent checkStatic
private static string.
protected static string.
public static string.
child checkInstance
private string.
protected string.
public string.
child checkStatic
private static string.
protected static string.
public static string.
child checkParent
protected string.
public string.
child checkParentStatic
protected static string.
public static string.