类成分而不是对象组成?

时间:2010-05-06 15:03:47

标签: php oop

我想要一个类属性引用另一个类,而不是它的对象,然后使用这个属性来调用类的静态方法。

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
    }
}

我有什么建议可以做到这一点?

因为我没有理由将它们作为对象,我想使用它的类。

2 个答案:

答案 0 :(得分: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!');

答案 1 :(得分:1)

由于您似乎只对一个特定的方法/函数感兴趣(没有进一步的契约/接口),您可以编写代码,无论它是静态方法还是对象方法都无关紧要(...嗯,对象方法......听起来不对,什么是正确的名字......)或简单的功能。

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