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 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝