yerine nesne kompozisyonu sınıf bileşimi?

2 Cevap php

Ben bir sınıf özelliği başka bir sınıf değil, kendi nesne referans olması ve daha sonra sınıfın statik yöntemi çağırmak için bu özelliği kullanmak istiyorum.

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

herhangi bir öneriniz nasıl ben bu başarabilirsiniz?

ben onları nesneleri yapma nedenim yok çünkü, ben bunun için sınıfları kullanmak istiyorum.

2 Cevap

(Daha fazla sözleşmeler / arayüzleri olmadan) bir özel yöntem / işlevi görünüşte sadece ilgilendiğiniz beri onu statik bir metod veya bir nesne yöntemi (... hm, nesne olsun fark etmez bir şekilde kod yazabilirsiniz yöntem ... bu doğru gelmiyor, doğru adı ...) ya da basit bir işlev budur.

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');

baskılar

LogDummy::write: foo
LogDummy->writeMe: bar
dummylog: baz
anonymous: ham

: call_user_func işlevini kullanın

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!');