phptools-docs
phptools-docs copied to clipboard
Offset access support
https://phpstan.org/writing-php-code/phpdoc-types#offset-access
<?php
/**
* @phpstan-type MyArray array{foo: int, bar: string}
*/
class HelloWorld
{
/** @return MyArray['bar'] */
public function getBar()
{
// this needs to return a string...
}
}
/**
* @template T of array<string, mixed>
*/
trait AttributeTrait
{
/** @var T */
private array $attributes;
/**
* @template K of key-of<T>
* @param K $key
* @param T[K] $val
*/
public function setAttribute(string $key, $val): void
{
// ...
}
/**
* @template K of key-of<T>
* @param K $key
* @return T[K]|null
*/
public function getAttribute(string $key)
{
return $this->attributes[$key] ?? null;
}
}
class Foo {
/** @use AttributeTrait<array{data:string}> */
use AttributeTrait;
}
$f = new Foo;
$f->setAttribute('bar', 5);
$f->setAttribute('foo', 3);
$v = $f->getAttribute('foo');