Last active
December 25, 2015 06:49
-
-
Save monmonmon/6934537 to your computer and use it in GitHub Desktop.
インスタンスメソッドの mixin (mixin.php から抜粋)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// mixin クラス | |
class MixinClass | |
{ | |
// インスタンスメソッド | |
// 注:第1引数に、mixin 先のクラスのインスタンスを表す "$that" が必要です。 | |
// 実際呼ぶ時は ->mixin_instance_method($message) ってなります。 | |
public function mixin_instance_method($that, $message, DateTime $date) | |
{ | |
print "これは MixinClass のインスタンスメソッドです $message ".$date->format('Y-m-d')."\n"; | |
print "Foo の public メンバ変数にアクセスすることも出来ます。 ".$that->foooooo."\n"; | |
} | |
} | |
// mixin 対象クラス | |
class Foo | |
{ | |
public $foooooo = 999; | |
// コンストラクタで MixinClass のインスタンスを作っときます | |
public function __construct() | |
{ | |
$this->mixin1 = new MixinClass(); | |
} | |
// __call をオーバーライドして、インスタンスメソッドの mixin を実装します | |
// インスタンスメソッド $method_name がこのクラスでも先祖クラスでも未定義な場合、ここへ到達。 | |
public function __call($method_name, $args) | |
{ | |
// Foo 自身を表す $this を引数リストの先頭に追加します | |
array_unshift($args, $this); | |
if (is_callable(array(&$this->mixin1, $method_name))) { | |
// MixinClass#$method_name を実行 | |
return call_user_func_array(array(&$this->mixin1, $method_name), $args); | |
} else { | |
// そんなインスタンスメソッドはどこにも見つかりませんでした。。。 | |
throw new BadMethodCallException(); | |
} | |
} | |
} | |
$foo = new Foo(); | |
print "// \$foo->mixin_instance_method\n"; | |
$foo->mixin_instance_method("yahoooooo!", new DateTime()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment