Referencia de PHP al método estático

I'm doing something like that on my project:

use Doctrine\ORM\EntityRepository;

class ArticlesType extends AbstractType {
    static function statusFilter(EntityRepository $er) {
        return $er->createQueryBuilder('x')->where('x.status = 1');

    public function buildForm(FormBuilder $builder, array $options)
                ->add('User', 'entity', array('class' => 'FP\MyBundle\Entity\Users',
#                                             'query_builder' => call_user_func(array('self','statusFilter'), ??)
                                              'query_builder' => function(EntityRepository $er) { return ArticlesType::statusFilter($er); }

any ideas on how to do a "nicer" call to the statusFilter method?

As you can see, I gave it a try with call_user_func, but I don't know which parameter to pass to it


preguntado el 27 de agosto de 11 a las 17:08

2 Respuestas

Puedes usar


Alternativamente, puede utilizar

call_user_func(array('self', 'statusFilter'), $er);

I understand this question better now. As @igorw suggest, Symfony is expecting a closure; however, this doesn't mean it can't be written nicer.

You could create a custom helper and then use it in your buildFom call.

function funcRef($func){
  return create_function('', "return call_user_func_array('{$func}', func_get_args());");

Then you could use it in your buildForm method as:

'query_builder' => funcRef("ArticlesType::statusFilter")

see it working here on

Respondido 31 ago 11, 00:08

what I don't get is this $er variable / It seems it doesn't "exist" (ie, I can't pass it to the function, but when I do function(EntityRepository $er), it "appears" - Lem0n

No. Symfony\Bridge\Doctrine\Form\Type\EntityType toma la query_builder option and passes it on to the Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList.

The query builder needs to be either an instance of Doctrine\ORM\QueryBuilder o Closure (anonymous function).

Also, call_user_func as suggested by macek would work in most cases, but it will not work in a closure, because it has a different scope. This might be addressed in PHP 5.4, but for now it will simply not work.

I would do it just as you have, using a closure and calling the static method from within it.

EDIT: And what you were initially trying to do won't work either, because in that case you would be calling the static method already. And that's not what you want. What you want is to pass a function, which is to be called at a later point in time.

Respondido 30 ago 11, 18:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.