Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I think if you are more specific , you should get a much better response.

I tried it with

Using php 8.1 and the static analyzer psalm, how can i specify template parameters for newly constructed classes?

and got a very good result including detailed explanations



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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: