Class Interface static self this,,,
と紛らわしいものが多く存在するので、今回をいい機会にまとめてみようと思いましたが、逆にコードが膨大になってしまいました。
ParentExample、Child1、InterfaceAを組み合わせて、$this、self::、などの使い方をまとめたチートシートだと思っていただければ。。。
<?php
class ParentExample {
// こちらの関数は以下でchildで継承される、継承した先で変更することができる。
public function bye() {
print "bye world";
}
// staticな関数
public static function staticfunc() {
print "this is static";
echo "\n";
}
public static $static_var = "this is a static var";
// こちらはstaticなのでインスタンス化しなくても呼び出せる。
public static function static_print_static_var() {
print self::$static_var;
echo "\n";
}
function test() {
self::bye();
echo "\n";
$this->bye();
echo "\n";
}
}
// 以下のインターフェースは定数を一つと関数を一つ持つ。
interface InterfaceA
{
public const word = "red";
public function printA();
}
class Child1 extends ParentExample implements InterfaceA
{
public function printA() {
print self::word;
echo "\n";
}
public function bye() {
print "bye universe";
}
}
$ch1 = new Child1();
print $ch1->printA(); //red
// staticなプロパティは矢印演算子によってアクセスすることはできない
// オブジェクトのインスタンスを生成せずにコールすることができる。
ParentExample::staticfunc(); // 'this is static'
ParentExample::static_print_static_var(); // 'this is a static var'
// インスタンスを生成した場合は矢印演算子を使う
$parent = new ParentExample();
// 同じtest関数だが、self、 $thisによって出力は異なる。
$parent->test(); // bye world, bye world
$ch1->test(); // bye world, bye universe
?>


