Skip to content
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

Allow new on objects #8723

Merged
merged 2 commits into from Nov 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -849,7 +849,9 @@ private static function analyzeConstructorExpression(
)) {
// fall through
}
} elseif ($lhs_type_part instanceof TMixed) {
} elseif ($lhs_type_part instanceof TMixed
|| $lhs_type_part instanceof TObject
) {
IssueBuffer::maybeAdd(
new MixedMethodCall(
'Cannot call constructor on an unknown class',
Expand All @@ -865,6 +867,9 @@ private static function analyzeConstructorExpression(
&& $stmt_class_type->ignore_nullable_issues
) {
// do nothing
} elseif ($lhs_type_part instanceof TNamedObject) {
$new_type = Type::combineUnionTypes($new_type, new Union([$lhs_type_part]));
continue;
} elseif (IssueBuffer::accepts(
new UndefinedClass(
'Type ' . $lhs_type_part . ' cannot be called as a class',
Expand Down
58 changes: 57 additions & 1 deletion tests/ClassTest.php
Expand Up @@ -795,6 +795,53 @@ interface I extends Traversable {}
abstract class C implements I {}
',
],
'newOnNamedObject' => [
'code' => '<?php
$o = new stdClass;
$o2 = new $o;
',
'assertions' => [
'$o2===' => 'stdClass',
],
],
'newOnObjectOfAnonymousClass' => [
'code' => '<?php
function f(): object {
$o = new class {};
return new $o;
}
',
],
'newOnObjectOfAnonymousExtendingNamed' => [
'code' => '<?php
function f(): Exception {
$o = new class extends Exception {};
return new $o;
}
',
],
'newOnObjectOfAnonymousClassImplementingNamed' => [
'code' => '<?php
interface I {}
function f(): I {
$o = new class implements I {};
return new $o;
}
',
],
'throwAnonymousObjects' => [
'code' => '<?php
throw new class extends Exception {};
',
],
'throwTheResultOfNewOnAnAnonymousClass' => [
'code' => '<?php
declare(strict_types=1);

$test = new class extends \Exception { };
throw new $test();
'
]
];
}

Expand Down Expand Up @@ -1151,7 +1198,16 @@ class Foo
class Bar {}
',
'error_message' => 'ReservedWord',
]
],
'newOnObject' => [
'code' => '<?php
function f(object $o): object
{
return new $o;
}
',
'error_message' => 'MixedMethodCall',
],
];
}
}