4

How can I indicate that a function/method accepts a class as a parameter? Either PHPDoc or type hinting would be sufficient, but neither seems to allow it.

Here's an example of what I'm thinking should work...

/**
 * @param $class class  A reference to a class that will be used to do something
 */
function doReallyWeirdStuff(class $class){
  $class::callStaticMethod();
}

I'm already aware of how to pass the class to this function. How do I indicate that you should do that?

2 Answers 2

4

Class names are merely strings, thus you must type hint them as string. You then need to check it's actually a class, at run-time, in your method:

/**
 * @param $class string  A reference to a class that will be used to do something
 */
function doReallyWeirdStuff(string $class){
  if (class_exists($class)) {
    $class::callStaticMethod();
  } else {
    throw \InvalidArgumentException;
  }
}

Note that, to enable strict adherence to string values (as would be required for class names), you need to enable strict type hinting:

declare(strict_types=1);

Otherwise, you could conceivably call like so:

doReallyWeirdStuff(M_PI);

which doesn't make much sense.

Sign up to request clarification or add additional context in comments.

5 Comments

Aha! Fantastic! Thank you
To pass in the class name you should use \MyNamespace\MyClass::class so that your IDE can refactor that code.
I will as soon as the waiting period expires. :)
declare(strict_types=1) is not required to enable scalar type hints. It is only required if you want PHP to throw an error if the exact type is not respected within the file (by default, PHP will convert another type to the type hinted, not throw an error)
You're likely right about the OP. Just stating an inaccuracy because lots of people other than the OP may come across your solution and take your words literally.
1

You can't do it with PHPDoc type hinting, unless you pass an actual object instance.

You can however abuse the PHP Doc type hinting.

string|Class $class
or
Class $class

This will produce very mixed results depending on what you're running. You'll lose some of the ability to run type checking without false negatives/positives.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.