0

I need help with this:

$foo = array ('Projects', 'Clients');

And I need to run functions from pre-installed library

$bar->getProjects()->data
$bar->getClients()->data 

etc. etc.

but I have it in the cycle. So I want something like

foreach($foo as $value)
  $return_value = $bar->get  >>>>$value<<<<  ()->data

How can this be done?

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
Jozko Golonka
  • 323
  • 1
  • 2
  • 11

3 Answers3

2

Please see How to call PHP function from string stored in a Variable:

foreach ($foo as $value) {
  $method = 'get' . $value;
  $return_value = $bar->$method()->data
}

or

foreach ($foo as $value)
  $return_value = $bar->{'get' . $value}()->data;
Community
  • 1
  • 1
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
1

I'd use reflection, a well documented, no magic 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;
}
Kris
  • 40,604
  • 9
  • 72
  • 101
  • IMO this is the cleanest solution. It also allows you to get tons of information about the arguments that the method takes, if you need to start passing arguments in this as well. – Colin M Feb 14 '13 at 13:30
  • 1
    @ColinMorelli The cleanest solution would be to not rely on dynamic method calls at all, but use interfaces instead. – KingCrunch Feb 14 '13 at 14:33
  • @KingCrunch Of course - and I'm sure you and I have much more programming experience. But you can't teach programming concepts like "building to interfaces" to someone who is new with programming as they aren't likely to see the benefit. Given what was within the realm of possible answers for this question - this is probably one of the better solutions. – Colin M Feb 14 '13 at 14:35
  • @KingCrunch: The question does not use interfaces but a rather random looking array of partial method names. No interfaces (or abstracts) mentioned there, so it would be weird and even more long winded if I had in my answer. Just going for the (imho) best tradeof between clean and pragmatic that could actually be used by the OP. – Kris Feb 14 '13 at 14:42
  • @Kris Yes, I know. I only commented ColinMorellis Statement about "the cleanest solution". – KingCrunch Feb 14 '13 at 16:09
0

There is a magic method for that: __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];
     }
}

You can also take a look at call_user_func

nicbou
  • 1,047
  • 11
  • 16