I want to be able to pass a class (not an object of the class) to a PHP function. The desired end-result of all of this is the ability to call static functions present on that class. Take, for example:
class MyClass extends Model
{
public static function doThing()
{
return static::callOtherClassFunction();
}
}
Now I have a function structured like this:
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.
Is what I want to do possible in PHP idiomatically? (ie without using Reflection to get the static function).
PS: This is tagged as 'Laravel' because 'MyClass' represents my 'Base Model' - the class that inherits directly from Laravel's "Model" 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
function do_thing_with_any_class(MyClass $class)
{
return $class::doThing();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.