次の問題があります。
<?php
/**
* Mother class defining static methods/attribute
*/
class A
{
public static $_greetings = 'Nothing';
public static function hi()
{
$c = get_called_class();
echo $c.' says '.$c::$_greetings.PHP_EOL;
}
public static function set($classname)
{
$c = get_called_class();
$g = $classname::$_greetings;
echo 'Setting '.$c.'::_greetings to '.$g.PHP_EOL;
$c::$_greetings = $g;
}
}
/**
* Children using inherited static method
*/
class C1 extends A
{
public function say() { self::hi(); }
}
class C2 extends A
{
public function say() { self::hi(); }
}
/**
* Data containers
*/
class D1
{
public static $_greetings = 'Hello World!';
}
class D2
{
public static $_greetings = 'Ola Chica!';
}
// ------------------------------------------------------------------------
/**
* The great misunderstanding...
*/
C1::set( 'D1' );
C2::set( 'D2' );
$c1 = new C1();
$c2 = new C2();
$c1->say();
$c2->say();
echo C1::$_greetings.PHP_EOL;
echo C2::$_greetings.PHP_EOL;
A
簡単に言うと、静的メッセージを出力するメソッドを定義します$_greetings
。このメッセージはA::set( classname )
、静的パラメーターも含むクラスの名前を入力に受け取るを使用して設定されます$_greetings
。say()
次に 2 つの子が来て、継承された static を使用して挨拶する独自のメソッドを定義しますhi()
。出力は次のようになると思います。
Setting C1::_greetings to Hello World!
Setting C2::_greetings to Ola Chica!
C1 says Hello World!
C2 says Ola Chica!
Hello World!
Ola Chica!
しかし、代わりに私は得る:
Setting C1::_greetings to Hello World!
Setting C2::_greetings to Ola Chica!
C1 says Ola Chica!
C2 says Ola Chica!
Ola Chica!
Ola Chica!
その理由が知りたい…!? 問題を理解するために時間をかけてくれる人たちに、前もって感謝します:)