Remix.run Logo
larsnystrom an hour ago

I've been writing PHP for 20 years now. It's my bread and butter.

The one thing I really wish PHP would add is structurally typed objects. I really miss it when moving back and forth between PHP and TypeScript.

They could call them anonymous objects if they want to (that would be a more culturally correct analogue to anonymous classes).

Like, I wish it was possible to do

  {
    string $mystring = $myvar,
  }
and have it be equivalent to

  new class($myvar) {
    public function __construct(
      readonly public string $mystring,
    ) {}
  }
and then be able to typehint it like

  function ({ string $mystring } $myobj) {
    echo $myobj->mystring;
  }
and honestly, why not go all the way and allow type definitions/aliases, something like

  type myobj_type = { string $mystring };
That'd be great.
idoubtit 27 minutes ago | parent [-]

You can do that. Of course, PHP's native types are quite limited, but a phpdoc syntax should work with static analysis tools. For instance:

    /** @psalm-type MyobjType = object{mystring: string} */

    /**
     * @param MyobjType $myobj
     */
    function (object $myobj): void

Here are some documentation and examples:

- For Psalm, see https://psalm.dev/docs/annotating_code/type_syntax/utility_t...

- For PHPstan, see https://phpstan.org/writing-php-code/phpdoc-types

It may work in your IDE (autocompletion, etc.) but there is no standard on this side. Some IDE have their own parsers, others use one of the LSPs for PHP.

larsnystrom 19 minutes ago | parent [-]

Yeah, at the moment we use arrays as anonymous objects and phpdoc+phpstan to verify the types, but I want it in the language. PHP already supports intersection and union types, it really feels like just skipping the naming part and going all in on structural typing is not that far fetched by now.