1

What is the correct returning object definition in psalm?

/** 
 * @psalm-return \stdClass{foo?: string}
 */
function returnObject(): \stdClass {
 $item2 = new \stdClass();
 $item2->foo = "asd";
    return $item2;
}

returnObject();

ERROR: InvalidDocblock - 19:1 - Unexpected brace character in docblock for returnObject

sandbox

Vixtrime
  • 443
  • 1
  • 5
  • 15

2 Answers2

1

You can do this with object, but you can't do this with any named class, including stdClass:

<?php
/** 
 * @psalm-return object{foo?: string}
 */
function returnObject(): object {
    $item2 = new stdClass();
    $item2->foo = "asd";
    return $item2;
}

$_v = returnObject();
/** @psalm-trace $_v */;
Psalm output (using commit 73ebe22): 

INFO: Trace - 12:24 - $_v: object{foo?:string}
weirdan
  • 2,499
  • 23
  • 27
0

The syntax you are using is not supported:

/** 
 * @psalm-return \stdClass{foo?: string}
 */

You should only indicate the type, followed by an optional description:

/** 
 * @psalm-return \stdClass Returns an object with the foo property set.
 */
Olivier
  • 13,283
  • 1
  • 8
  • 24
  • So do you mean that I can't specify object fields description using stdClass as a return type inside psalm annotations? – Vixtrime Jul 27 '23 at 21:30
  • @Vixtrime Where did you see in Psalm documentation that you could use such a syntax? – Olivier Jul 28 '23 at 06:47