Skip to content

Commit 268dbfe

Browse files
committed
Detect invalid uses of "static" earlier
1 parent e8bf890 commit 268dbfe

File tree

3 files changed

+25
-6
lines changed

3 files changed

+25
-6
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
--TEST--
2+
Static type outside class generates compile error
3+
--FILE--
4+
<?php
5+
6+
function test(): static {}
7+
8+
?>
9+
--EXPECTF--
10+
Fatal error: Cannot use "static" when no class scope is active in %s on line %d

Zend/tests/type_declarations/static_type_return.phpt

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,6 @@ class B extends A {
2626

2727
class C extends B {}
2828

29-
function test(): static {
30-
return new stdClass;
31-
}
32-
3329
$a = new A;
3430
$b = new B;
3531

@@ -57,12 +53,19 @@ try {
5753
}
5854

5955
echo "\n";
56+
$test = function($x): static {
57+
return $x;
58+
};
59+
6060
try {
61-
var_dump(test());
61+
var_dump($test(new stdClass));
6262
} catch (TypeError $e) {
6363
echo $e->getMessage(), "\n";
6464
}
6565

66+
$test = $test->bindTo($a);
67+
var_dump($test($a));
68+
6669
?>
6770
--EXPECT--
6871
object(A)#3 (0) {
@@ -83,4 +86,6 @@ object(A)#3 (0) {
8386
}
8487
Return value of A::test4() must be of type static|array, instance of A returned
8588

86-
Return value of test() must be an instance of static, instance of stdClass returned
89+
Return value of {closure}() must be an instance of static, instance of stdClass returned
90+
object(A)#1 (0) {
91+
}

Zend/zend_compile.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5464,6 +5464,10 @@ static zend_type zend_compile_single_typename(zend_ast *ast)
54645464
{
54655465
ZEND_ASSERT(!(ast->attr & ZEND_TYPE_NULLABLE));
54665466
if (ast->kind == ZEND_AST_TYPE) {
5467+
if (ast->attr == IS_STATIC && !CG(active_class_entry) && zend_is_scope_known()) {
5468+
zend_error_noreturn(E_COMPILE_ERROR,
5469+
"Cannot use \"static\" when no class scope is active");
5470+
}
54675471
return (zend_type) ZEND_TYPE_INIT_CODE(ast->attr, 0, 0);
54685472
} else {
54695473
zend_string *class_name = zend_ast_get_str(ast);

0 commit comments

Comments
 (0)