2016-01-22 86 views
0

我与第三方类的工作,我需要能够运行的代码段的两种方式,这取决于一个...PHP变量多对象属性

$reader->get()->first()->each(function($obj) 
{ 
    // Do stuff 
} 

OR

$reader->get()->each(function($obj) 
{ 
    // Do stuff 
} 

我一直能够与像可变调用属性...

$a = 1; 
$obj->{"$a"} 

但不幸的是下面的不工作...

if (some scenario) 
{ 
$a = "get()->first()"; 
} 
else 
{ 
$a = "get()"; 
} 

$reader->{"$a"}->each(function($obj) 

我的问题是我不知道如何短语问题谷歌...我假设有上述问题的解决方案。

在此先感谢您的帮助!

回答

1

您只能使用->{$variable}获取类本身的属性和方法名称,不能将PHP语法如->放在那里。你可以做的是使用函数变量:

function get_all($reader) { 
    return $reader->get(); 
} 
function get_first($reader) { 
    return $reader->get()->first(); 
} 

$a = 'get_all'; // or $a = 'get_first'; 
$a($reader)->each(function($obj) { 
    // do stuff 
}); 
+0

非常感谢你,工作就像一个魅力! – SoWizardly

0

替代巴尔马尔的答案,哪个imho有点清晰。

$it = function($obj) { 
    // do stuff 
}); 

if (some_scenario) { 
    $reader->get()->first()->each($it); 
} else { 
    $reader->get()->each($it); 
} 

还有一个解决办法:

if (some_scenario) { 
    $foo = $reader->get()->first(); 
} else { 
    $foo = $reader->get(); 
} 
$foo->each(function($obj) { 
    // do stuff 
});