开发者

PHP reference to static method

开发者 https://www.devze.com 2023-03-31 09:40 出处:网络
I\'m doing something like that on my project: use Doctrine\\ORM\\EntityRepository; class ArticlesType extends AbstractType {

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)
    {
        $builder
                ->add('User', 'entity', array('class' => 'FP\MyBundle\Entity\Users',
#                                             'query_builder' => ca开发者_开发知识库ll_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

thanks


You can use

self::statusFilter($er);

Alternatively, you can use

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 tehplayground.com


No. Symfony\Bridge\Doctrine\Form\Type\EntityType takes the 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 or a 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消