-
Notifications
You must be signed in to change notification settings - Fork 659
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
"Cannot call constructor on an unknown class" when creating class from variable #8628
Comments
Hey @JoolsMcFly, can you reproduce the issue on https://psalm.dev ? |
You seem to know the constructor doesn't have parameters, so I guess you have some kind of insight into what kind of class is pushed to you there. Psalm need to know that too because otherwise, it can't guarantee you won't get a php error for passing wrong parameters. So if you can document your $classNames as If you're not able to do that, it means you have an inherently unsafe construct and you'll have to suppress the issue instead of trying to fix it |
Right. I know constructors I am dealing with have no params so should be OK for now to use ReflectionClass (which solves my problem)? try {
$cl = new ReflectionClass($className);
$class = $cl->newInstance();
if ($class instanceof SomeInterface) {
// do something
}
} catch (ReflectionException $e) {
} I now need to figure out why phpstan reports |
If you know you have a About PHPStan, I'd assume they have a partial stub that doesn't document this exception |
Thanks for your follow up. I originally had this: foreach ($classNames as $className) {
if (!class_exists($className)) {
continue;
}
$class = new $className();
if ($class instanceof SomeInterface) {
// blabla
}
} but I still had the error message on |
Something like that should work: https://psalm.dev/r/f95a929e11 |
I found these snippets: https://psalm.dev/r/f95a929e11<?php
$classNames = ['aaa', 'bbb'];
foreach ($classNames as $className) {
if (!is_a($className, SomeInterface::class, true)) {
continue;
}
$_class = new $className();
}
interface SomeInterface{}
|
Works like a charm. Thanks! |
Hi all.
I need to create new classes from an array of class names. I have added
allowStringToStandInForClass="true"
topsalm.xml
but I still get the following error:Si I tried to add more context:
Adding
class_exists
does not do the trick. Any ideas how to fix the reported error?Thanks!
The text was updated successfully, but these errors were encountered: