如何在php中使用反射从数组转换为数据结构

时间:2016-02-24 07:30:47

标签: php reflection

我在php.net上看到SplFixedArray有"优点是它允许更快的阵列实现"在常规数组上。有些我也想了解反思。我似乎无法让它发挥作用:

$refDLL = new ReflectionClass( 'SplDoublyLinkedList' );
$method = $refDLL->getMethod( 'add' );
$keys = array_keys( $_GET );
$count = count( $keys );
$oIndex = 0;
while( $oIndex < $count )
{
    $method( // <-- this seems to be the point of failure
        $oIndex, 
        $_GET[$keys[$oIndex]] 
    );
    $oIndex++;
}

错误:

PHP Fatal error:  Uncaught Error: Function name must be a string in 
C:\inetpub\wwwroot\objstr.php:26
Stack trace:
#0 {main}
  thrown in C:\inetpub\wwwroot\objstr.php on line 26

2 个答案:

答案 0 :(得分:0)

我找到了答案:

$refDLL = new ReflectionMethod( 'SplDoublyLinkedList', 'add' );
$keys = array_keys( $_GET );
$count = count( $keys );
$oIndex = 0;
$sdll = new SplDoublyLinkedList();
while( $oIndex < $count )
{

    $refDLL->invoke( $sdll, 
        $oIndex, 
        $_GET[$keys[$oIndex]] 
    );
    $oIndex++;
}

$sdll->rewind();

while( $sdll->valid() )
{
    print_r( $sdll->key() ); echo '<br />';
    print_r( $sdll->current() ); echo '<br />';
    $sdll->next();
}

查询:

?zero=pZ0&one=pO1

输出:

0
pZ0
1
pO1

答案 1 :(得分:0)

可以更轻松地完成。反射getMethod()不返回闭包但是ReflectionMethod所以当你使用getMethod()时你可以调用它

 $method = $refDLL->getMethod( 'add' );
 $method->invoke($sdll, $oIndex, $_GET[$keys[$oIndex]] );

出现错误是因为你尝试调用方法,因为它是关闭但不是'。

编辑:

只需更改

$oIndex = 0;
$sdll = new SplDoublyLinkedList();
while( $oIndex < $count )
{
    $method( // <-- this seems to be the point of failure
        $oIndex, 
        $_GET[$keys[$oIndex]] 
    );
    $oIndex++;
}

$sdll = new SplDoublyLinkedList();

for ($oIndex = 0; $oIndex < $count; ++$oIndex )
{
    $method->invoke($sdll, $oIndex, $_GET[$keys[$oIndex]] );
}

顺便说一句,你使用while循环可以很容易地用for循环替换它。