Skip to content

Instantly share code, notes, and snippets.

@ewilan-riviere
Created November 22, 2023 08:00
Show Gist options
  • Save ewilan-riviere/86b11e53743aad142cb8d8b704fb7777 to your computer and use it in GitHub Desktop.
Save ewilan-riviere/86b11e53743aad142cb8d8b704fb7777 to your computer and use it in GitHub Desktop.
PHP array|object typed on VSCode.

PHP array|object typed on VSCode.

With vscode-intelephense extension (1.10.0 - 2023-11-05).

Array/Object shapes via annotations

/** @param array{foo:string, bar:int} $arrayShape */ or /** @return object{foo:string, bar:int} */

Improved type inference

For new $className expressions where $className is of type class-string

Annotation to ignore diagnostics/problems on statement level

/** @disregard [OPTIONAL CODE] [OPTIONAL DESCRIPTION] */. For example /** @disregard P1013 method exists on runtime type */

Conditional return types

Must be encapsulated in parentheses.

For example - /** @return ($param is string ? string : object) */, /** @return (T is string ? string : object) */

<?php

/** @var array{foo:string, bar:int} $arrayShape */
$arrayShape = ['foo' => 'foo', 'bar' => 1];

$foo = $arrayShape['foo']; // autocomplete works, type is string
$bar = $arrayShape['bar']; // autocomplete works, type is int

/** @var object{foo:string, bar:int} $objectShape */
$objectShape = (object)['foo' => 'foo', 'bar' => 1];

$foo = $objectShape->foo; // autocomplete works, type is string
$bar = $objectShape->bar; // autocomplete works, type is int

/** @var array{foo:string, bar:int}[] $arrayOfArrayShapes */
$arrayOfArrayShapes = [
    ['foo' => 'foo', 'bar' => 1],
    ['foo' => 'foo', 'bar' => 1],
];

$foo = $arrayOfArrayShapes[0]['foo']; // autocomplete works, type is string
$bar = $arrayOfArrayShapes[0]['bar']; // autocomplete works, type is int

/** @var object{foo:string, bar:int}[] $arrayOfObjectShapes */
$arrayOfObjectShapes = [
    (object)['foo' => 'foo', 'bar' => 1],
    (object)['foo' => 'foo', 'bar' => 1],
];

$foo = $arrayOfObjectShapes[0]->foo; // autocomplete works, type is string
$bar = $arrayOfObjectShapes[0]->bar; // autocomplete works, type is int
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment