接受两个不同的模型实例作为函数参数 php

Accept two different model instances as a function argument php

我正在编写一个辅助函数,通过检查任何相关字段是否不等于 null 来检查我的数据库中是否存在任何地址信息。

因此,我需要在函数中接受两个模型作为参数。

传递的变量可以是其中之一。

对于一个只接受一种模型的函数,我可以这样做:

function check_for_address_info(App\Customer $customer) {
    // other unrelated stuff
}

有没有办法接受这两种模型,或者我必须通过执行以下操作在函数中手动检查它:

function check_for_address_info($param) {
  if(!is_a($param, 'App\Customer' || !is_a($param, 'App\Supplier')) {
    // not an instance of either model
    return false;
  }

  // do stuff as normal
}

关于如何接受两个不同的模型作为函数参数有什么想法吗?

我在Laravel 5.8。

有两种方法,如果在继承方面有意义,您可以扩展父模型并将其声明为参数的类型。这将在 运行 时间进行检查,如果您将错误的类型传递给该方法,则会提供错误。

public class Profile extends Model {
}

public class Customer extends Profile {
}

public class Supplier extends Profile {
}

function check_for_address_info(App\Profile $customerOrSupplier) {
}

在弱类型语言中,具有泛型参数是很常见的。 PHP 解决这个问题的方法是,您可以在 PHP 文档块中声明它。这不会在 运行 时间检查类型,主要用于类型提示、文档和静态分析工具。

/**
 * @parameter \App\Customer|\App\Supplier $customerOrSupplier
 **/
function check_for_address_info($customerOrSupplier) {
}