代码之家  ›  专栏  ›  技术社区  ›  Dimitrios Desyllas

使用php的调用方法调整类:传递参数

  •  0
  • Dimitrios Desyllas  · 技术社区  · 6 年前

    基于 answer __call 方法,以便具有将存储库作为服务调用的通用方法:

    namespace AppBundle\Services;
    
    use Doctrine\ORM\EntityManagerInterface;
    
    class RepositoryServiceAdapter
    {
            private $repository=null;
    
            /**
            * @param EntityManagerInterface the Doctrine entity Manager
            * @param String $entityName The name of the entity that we will retrieve the repository
            */
            public function __construct(EntityManagerInterface $entityManager,$entityName)
            {
                $this->repository=$entityManager->getRepository($entityName)
            }
    
            public function __call($name,$arguments)
            {     
              if(empty($arguments)){ //No arguments has been passed
                 $this->repository->$name();
              } else {
                 //@todo: figure out how to pass the parameters
                 $this->repository->$name();
              }
            }
    }
    

    存储库方法将具有以下形式:

    public function aMethod($param1,$param2)
    {
      //Some magic is done here
    }
    

    $arguments

            public function __call($name,$arguments)
            {
               $this->repository->$name($argument[0],$argument[1],$argument[2]);
            }
    

    但这似乎不切实际,对我来说不是一个具体的解决方案,因为一个方法可以有多个参数。我想我需要解决以下问题:

    1. 如何在迭代数组时传递参数 ?
    1 回复  |  直到 6 年前
        1
  •  1
  •   Nigel Ren    6 年前

    从PHP5.6开始 argument unpacking 它能让你在使用后做你想要的事情 ...

    $this->repository->$name($argument[0],$argument[1],$argument[2]);
    

    变成。。。

    $this->repository->$name(...$argument);
    

    这将传递任何数字或参数,就像它们是单独的字段一样。

    推荐文章