Just tried it with a PHP question regarding type safety, and it completely made up some lovely syntax I wish the language had, but doesn’t. It got lots of things right, but that one crucial detail wrong.
That makes it the same dangerous tool as ChatGPT that is useful to experienced coders, but utterly disastrous for newcomers.
> Question:
> in php using psalm, how can i specify template parameters for newly constructed instances?
> ANSWER
// Create a new instance of MyClass with a string parameter
$my_instance = new MyClass<string>("Hello World!");
// Call the getValue method to retrieve the value
$value = $my_instance->getValue();
// The $value variable is now a string
echo gettype($value); // outputs "string"
> To create a new instance of MyClass with a specific parameter type, we use the syntax new MyClass<string>("Hello World!");, where string is the type we want to use for T, and "Hello World!" is the value we want to pass to the constructor.
> We can then call the getValue method to retrieve the value, which will be of type string.
Oh yeah? I get the following delightful but equally wrong snippet:
>Another way to achieve a similar effect is to use PHP's built-in generics feature. This feature was introduced in PHP 8.0 and allows you to specify the type of a class property or method argument as a generic type. Here's an example:
class MyList<T> {
/** @var array<T> */
private $items = [];
public function add(T $item): void {
$this->items[] = $item;
}
public function get(int $index): T {
return $this->items[$index];
}
}
> In this example, we use the <T> syntax to specify that MyList is generic and that it has a type parameter T. We then use the T type in the same way as before to specify the type of the $items property and the add and get methods.
> Using generics in this way has the advantage of being built into PHP, so you don't need to use any external libraries or tools. However, it can be a bit more verbose than using PHPDoc comments, and it doesn't provide the same level of type checking as Psalm.
That makes it the same dangerous tool as ChatGPT that is useful to experienced coders, but utterly disastrous for newcomers.
> Question: > in php using psalm, how can i specify template parameters for newly constructed instances?
> ANSWER
> To create a new instance of MyClass with a specific parameter type, we use the syntax new MyClass<string>("Hello World!");, where string is the type we want to use for T, and "Hello World!" is the value we want to pass to the constructor.> We can then call the getValue method to retrieve the value, which will be of type string.