phptools-docs icon indicating copy to clipboard operation
phptools-docs copied to clipboard

Offset access support

Open ging-dev opened this issue 1 year ago • 0 comments

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');

ging-dev avatar Aug 18 '24 03:08 ging-dev