2010-05-06 113 views
0

我想要一個類屬性引用另一個類,而不是它的對象,然後使用該屬性來調用該類的靜態方法。類組合而不是對象組合?

class Database { 
    private static $log; 

    public static function addLog($LogClass) { 
     self::$log = $LogClass; 
    } 

    public static function log() { 
     self::$log::write(); // seems not possible to write it like this 
    } 
} 

如何我可以做到這一點?

因爲我沒有理由讓它們成爲對象,所以我想爲它使用類。

回答

1

既然你貌似只有在一個特定的方法/功能感興趣(沒有更多的合同/接口),你可以在一個方式,它不要緊寫代碼無論是靜態方法還是對象方法(... 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 
+0

對象的方法聽起來不錯,給我,但你可以把它叫做一個實例方法,也 – Gordon 2010-05-06 15:43:57

2

使用call_user_func功能:

class Logger { 
    public static function write($string) { 
     echo $string; 
    } 
} 

class Database { 
    private static $log; 

    public static function addLog($LogClass) { 
     self::$log = $LogClass; 
    } 

    public static function log($string) { 
     call_user_func(array(self::$log, 'write'), $string); 
    } 
} 

$db = new Database(); 
$db->addLog('Logger'); 
$db->log('Hello world!');