簡體   English   中英

如何檢查php中的閉包?

[英]How to inspect a closure in php?

我有一個正在傳遞閉包的函數。 我想找出閉包派生自的方法的名稱。 當我調用print_r時,它輸出:

Closure Object
(
  [static] => Array
    (
      [listener] => Event_Subscriber_Calq@vendor_product_created
      [container] => Illuminate\Foundation\Application Object
...

我如何訪問該偵聽器值? 我試過 ->static、::$static、getStatic(),我想不出任何方法來獲取值。

目前,我的計划是使用輸出緩沖來捕獲 var_dump 的輸出。 我不能為此使用 print_r,因為閉包包含對引用自身的對象的引用,而 print_r 需要很長時間來處理遞歸。 我也不能使用 var_export,因為它沒有在輸出中包含我想要的值。 所以,這是我的解決方案:

ob_start();
var_dump($closure);
$data = ob_get_clean();
$data = preg_replace('#^([^\n]*\n){4}#', '', $data);
$data = preg_replace('#\n.*#', '', $data);
$data = preg_replace('#.*string.[0-9]+. "(.*)".*#', '\1', $data);
list($class, $method) = explode('@', $data);

這是可怕的。 有沒有另一種方法可以做到這一點? 也許使用反射?

我知道這篇文章很舊,但如果有人在尋找信息,你需要使用 ReflectionFunction:

$r = new ReflectionFunction($closure);
var_dump($r, $r->getStaticVariables(), $r->getParameters());

問候,亞歷克斯

在最近的一個項目中,我決定采用一種使用包裝類的聲明式方法。 該類允許設置描述回調源的自由格式字符串,並且可以用作閉包的直接替換,因為它實現了__invoke()方法。

例子:

use ClosureTools;

$closure = new NamedClosure(
    function() {
        // do something
    }, 
    'Descriptive text of the closure'
);

// Call the closure
$closure();

要訪問有關關閉的信息:

if($closure instanceof NamedClosure) {
    $origin = $closure->getOrigin();
}

由於原點是自由形式的字符串,因此可以根據用例將其設置為對識別閉包有用的任何內容。

這是類骨架:

<?php

declare(strict_types=1);

namespace ClosureTools;

use Closure;

class NamedClosure
{
    /**
     * @var Closure
     */
    private $closure;

    /**
     * @var string
     */
    private $origin;

    /**
     * @param Closure $closure
     * @param string $origin
     */
    public function __construct(Closure $closure, string $origin)
    {
        $this->closure = $closure;
        $this->origin = $origin;
    }

    /**
     * @return string
     */
    public function getOrigin() : string
    {
        return $this->origin;
    }

    public function __invoke()
    {
        return call_user_func($this->closure, func_get_args());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM