1

I have a bunch of functions depending on a variable, I want to be able to do something like this:
(It returns an error hence the problem I'm unable to solve)

function($x) {
    fetch.$x.() // if x=Name I would like it to execute fetchName()...and so on 
}

and something like this

function($x) {
    $article = new \Cc\WebBundle\Entity\$X(); 
    // if x='name' to be executed Cc\WebBundle\Entity\name()
}
0

2 Answers 2

1

Sure, you could do that:

$basename = "fetch";
$key = ...; // your logic for generating the rest of function's name

$functionName = $basename . $key;
$functionName(); // execute function

Now, the tricky part would be if functions contain arbitrary set of arguments. In that case you should use call_user_func_array (docs).

As for creating of objects, meagar explained here please clear how to achieve that.

P.S. This, in fact, has very little to do with Symfony2. This is a pure PHP question ;)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks . with trial and error worked perfectly saved me hundreds of line codes . Ps:symfony2 ...that was just the context
0

Personally, I use the handy call_user_func_array() function like this:

<?php

$class = 'MyClassName';
$method = 'someMethod';
$parameters = array('foo', 'bar', 'baz');

call_user_func_array(array($class, $method), $parameters);

I imagine you would need to escape back-slashes in any name-spaced class names though, i.e. MCB\\MyClassName.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.