我需要帮助:
$foo = array ('Projects', 'Clients');
我需要从预安装的库中运行函数
$bar->getProjects()->data
$bar->getClients()->data
等。等
但我在周期中拥有它。所以我想要像
这样的东西foreach($foo as $value)
$return_value = $bar->get >>>>$value<<<< ()->data
如何做到这一点?
答案 0 :(得分:2)
请参阅How to call PHP function from string stored in a Variable:
foreach ($foo as $value) {
$method = 'get' . $value;
$return_value = $bar->$method()->data
}
或
foreach ($foo as $value)
$return_value = $bar->{'get' . $value}()->data;
答案 1 :(得分:1)
我会使用反射,记录良好,没有神奇的API:
<?php
$foo = array ('Projects', 'Clients');
$bar = new MyAwesomeClass();
var_dump(invokeMultipleGetters($bar, $foo));
// could also make this a method on MyAwesomeClass...
function invokeMultipleGetters($object, $propertyNames)
{
$results = array();
$reflector = new ReflectionClass($object);
foreach($propertyNames as $propertyName)
{
$method = $reflector->getMethod('get'.$propertyName);
$result = $method->invoke($bar);
array_push($results, $result)
}
return $results;
}
答案 2 :(得分:0)
有一种神奇的方法:__call
function __call($method, $params) {
$var = substr($method, 3);
if (strncasecmp($method, "get", 3)) {
return $this->$var;
}
if (strncasecmp($method, "set", 3)) {
$this->$var = $params[0];
}
}
您还可以查看call_user_func