dongpan8439 2018-03-26 11:09
浏览 75
已采纳

为函数中的参数设置多个实例类型

I've done some googling on this and can't seem to find much assistance. However, I was wondering if there is a way to check multiple Instance types for an argument in a function, so to check whether it is an instance of the User model or another model for example and if it is one of the two then allow it through. If not, throw an error. I am using PHP and Laravel.

The use case here is that I am migrating a database from SQL to Mongo, so for an interim period I'll have two user models (User and MongoUser) and I want to check against each of these to determine whether the argument is a User instance of some form.

public function setTo(User $user)
    {
        $this->user()->associate($user);

        return $this;
    }

Last resort, I can duplicate the functions, but this seems unnecessary duplication. And I'd rather not remove the Instance check altogether.

I wanted to know if there was a way to achieve this? If not, I'd be interested to hear people's thoughts on the best way to handle this generally.

Thanks!

  • 写回答

1条回答 默认 最新

  • douzhannao5357 2018-03-26 11:22
    关注

    Here's what you could do:
    Let both classes (User and MongoUser) extend a base class (UserBase??) and check for that.

    <?php
    
    class base {
    }
    
    class A extends base {
    }
    
    class B extends base {
    }
    
    class C {
    }
    
    function test(base $x) {
        var_dump($x);
    }
    
    
    test(new base()); // good
    test(new A());  // good
    test(new B());  // good
    test(new C());  // throws error because class C doesn't extend base class
    

    Another possibility would be to leave out the restriction in the method-declaration and do a manual test:

    public function setTo($user)
    {
        if($user instanceof User || $user instanceof MongoUser) {
            echo "is an instance of User or MongoUser";
            $this->user()->associate($user);
    
            return $this;
        } else {
           // throw an erorr
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么