既然你貌似只有在一個特定的方法/功能感興趣(沒有更多的合同/接口),你可以在一個方式,它不要緊寫代碼無論是靜態方法還是對象方法(... hm,對象方法...聽起來不對,什麼是正確的名稱...)或簡單的函數。
class LogDummy {
public static function write($s) {
echo 'LogDummy::write: ', $s, "\n";
}
public function writeMe($s) {
echo 'LogDummy->writeMe: ', $s, "\n";
}
}
class Database {
private static $log=null;
public static function setLog($fnLog) {
self::$log = $fnLog;
}
public static function log($s) {
call_user_func_array(self::$log, array($s));
}
}
// static method
Database::setLog(array('LogDummy', 'write'));
Database::log('foo');
// member method
$l = new LogDummy;
Database::setLog(array($l, 'writeMe'));
Database::log('bar');
// plain old function
function dummylog($s) {
echo 'dummylog: ', $s, "\n";
}
Database::setLog('dummylog');
Database::log('baz');
// anonymous function
Database::setLog(function($s) {
echo 'anonymous: ', $s, "\n";
});
Database::log('ham');
打印
LogDummy::write: foo
LogDummy->writeMe: bar
dummylog: baz
anonymous: ham
對象的方法聽起來不錯,給我,但你可以把它叫做一個實例方法,也 – Gordon 2010-05-06 15:43:57