Kapatma iç sınıf bakmadan PHP Kapatma için test

0 Cevap php

PHP manual for anonymous functions (yani, Kilitler) şöyle der:

Anonim işlevler Kapatma sınıfı kullanılarak uygulanır. Bu uygulama detay ve should not be relied upon.

(Emphasis is my own)

Bu sınama doğru döndüren böyle bir değişkeni, test etmek mümkün mü değişken Kapatma yalnızca, without referring to the Closure class?

Diğer bir deyişle, nasıl ben $bar bir anonim işlev şey ama ne zaman bir hata yükseltmek olacağı aşağıdaki gibi yazabilirsiniz:

function foo(Closure $bar) {
    $bar();
}

EDIT: Alınan yanıtlara dayanarak, burada bir örnek testtir.

Notlar:

  1. It seems there is no way to differentiate between Functors and Closures, and that the test is probably just as 'implementation specific' as using the Closure class.
  2. (Görünüşte açık) ReflectionFunction::isClosure() yöntem hemen hemen işe yaramaz gibi görünüyor: Eğer ReflectionFunction aslında (bir kapatma dışında bir sınıf alamaz örneği olabilir emin olmak için gerekli kontrolleri yaptık zaman ), tüm diğer seçenekleri eledik.
  3. 5.3.0 Eğer ReflectionClass ($ kapatma) - bu yana değişti (ben söyledim) ancak> hasMethod ('__invoke') döndürülen false, bu nedenle bu Funktor karşı bir test olarak kullanılabilir. Bu da çözeltinin zaaf vurgulamaktadır.
  4. php.net/manual/en/class.closure.php: PHP 5.4 Eğer Kapatma bir Kapatma olmanın güvenebilirsiniz gibi - dan Gordon Takip

Kod:

/**
 * Return true if and only if the passed argument is a Closure.
 */
function testClosure($a) {
    // Must be Callback, Labmda, Functor or Closure:
    if(!is_callable($a)) return false;

    // Elminate Callbacks & Lambdas
    if(!is_object($a)) return false;

    // Eliminate Functors
    //$r = new ReflectionFunction($a); <-- fails if $a is a Functor
    //if($r->isClosure()) return true;

    return false;
}

Test durumda:

//////////// TEST CASE /////////////

class CallBackClass {
    function callBackFunc() {
    }
}

class Functor {
    function __invoke() {
    }
}

$functor = new Functor();
$lambda = create_function('', '');
$callback = array('CallBackClass', 'callBackFunc');
$array = array();
$object = new stdClass();
$closure = function() { ; };

echo "Is it a closure? \n";
echo "Closure: " . (testClosure($closure) ? "yes" : "no") . "\n";
echo "Null: "  . (testClosure(null) ? "yes" : "no") . "\n";
echo "Array: " . (testClosure($array) ? "yes" : "no") . "\n";
echo "Callback: " . (testClosure($callback) ? "yes" : "no")  . "\n";
echo "Labmda: " .(testClosure($lambda) ? "yes" : "no") . "\n";
echo "Invoked Class: " . (testClosure($functor) ? "yes" : "no")  . "\n";
echo "StdObj: " . (testClosure($object) ? "yes" : "no") . "\n";

-

0 Cevap