简体   繁体   English

如何将 Class 作为参数传递给 PHP function

[英]How do I pass a Class as a parameter to a PHP function

I want to be able to pass a class (not an object of the class) to a PHP function.我希望能够将 class(不是该类的 object)传递给 PHP ZC1C425268E68385D1AB570。 The desired end-result of all of this is the ability to call static functions present on that class.所有这一切所需的最终结果是能够调用 class 上存在的 static 函数。 Take, for example:举个例子:

class MyClass extends Model
{
  public static function doThing()
  {
    return static::callOtherClassFunction();
  }
}

Now I have a function structured like this:现在我有一个 function 结构如下:

function do_thing_with_any_class($class)
{
  return $class::doThing();
}

But, if I call do_thing_with_any_class(MyClass::class) , I get a syntax error.但是,如果我调用do_thing_with_any_class(MyClass::class) ,我会收到语法错误。

Is what I want to do possible in PHP idiomatically?我想在 PHP 惯用地做些什么? (ie without using Reflection to get the static function). (即不使用反射获得 static 函数)。

PS: This is tagged as 'Laravel' because 'MyClass' represents my 'Base Model' - the class that inherits directly from Laravel's "Model" class. PS:这被标记为“Laravel”,因为“MyClass”代表我的“基本模型”——直接从 Laravel 的“模型”class 继承的 class。 But the question is definitely more general than that.但这个问题肯定比这更笼统。

You can pass the class itself as a parameter and a variable as the instance like so您可以将 class 本身作为参数传递,并将变量作为实例传递,如下所示

function do_thing_with_any_class(MyClass $class)
{
  return $class::doThing();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM