Newsgroups: php.internals Path: news.php.net Xref: news.php.net php.internals:125405 X-Original-To: internals@lists.php.net Delivered-To: internals@lists.php.net Received: from php-smtp4.php.net (php-smtp4.php.net [45.112.84.5]) by qa.php.net (Postfix) with ESMTPS id 175941A00BD for ; Tue, 3 Sep 2024 06:41:33 +0000 (UTC) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=php.net; s=mail; t=1725345809; bh=crhXp9RZx3GTirI+iE5WVOUh0FmrJQn9ICYH/ddf+MI=; h=Date:From:To:Cc:In-Reply-To:References:Subject:From; b=jYpROKAuuC26cytjBcWs9JM/jjJpfLdMySDjW2uzyWNaujitUxakm1GW+Sb2pLVKc BTRHcxpD+jGQyJRdAv4BocE/pjy0pwX4mMx9SFH3G5hA3gGBb7UwkTCEmygXJDu2Z+ Nrwjw31TelGRlPIqYmvlvUCEugv6aKrzHCaIyxJ6lUZJMqaNkqmxXuXN6A5v9JEc2d 0VHk54FFyjJVpLpXnBu8W/bfpaZfP+tYwkwiLEaHwMjiw9WH+O3QktCU7/dXNL8O5H yFRjfSkM1Cd3xKeMb/dGRzUiM6mLImqTzP1NUc1AqfXkJHSTrs87QvXcWSOGBDH2Nf /X9q0BQT4i7bA== Received: from php-smtp4.php.net (localhost [127.0.0.1]) by php-smtp4.php.net (Postfix) with ESMTP id D1AA3180032 for ; Tue, 3 Sep 2024 06:43:27 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 4.0.0 (2022-12-13) on php-smtp4.php.net X-Spam-Level: X-Spam-Status: No, score=-0.1 required=5.0 tests=BAYES_50,DKIM_SIGNED, DKIM_VALID,DKIM_VALID_AU,DKIM_VALID_EF,DMARC_MISSING,HTML_MESSAGE, RCVD_IN_DNSWL_LOW,RCVD_IN_MSPIKE_H4,RCVD_IN_MSPIKE_WL,SPF_HELO_PASS, SPF_PASS autolearn=no autolearn_force=no version=4.0.0 X-Spam-Virus: No X-Envelope-From: Received: from fhigh5-smtp.messagingengine.com (fhigh5-smtp.messagingengine.com [103.168.172.156]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by php-smtp4.php.net (Postfix) with ESMTPS for ; Tue, 3 Sep 2024 06:43:27 +0000 (UTC) Received: from phl-compute-03.internal (phl-compute-03.nyi.internal [10.202.2.43]) by mailfhigh.nyi.internal (Postfix) with ESMTP id 4D32B114008C; Tue, 3 Sep 2024 02:41:29 -0400 (EDT) Received: from phl-imap-09 ([10.202.2.99]) by phl-compute-03.internal (MEProxy); Tue, 03 Sep 2024 02:41:29 -0400 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=bottled.codes; h=cc:cc:content-type:content-type:date:date:from:from :in-reply-to:in-reply-to:message-id:mime-version:references :reply-to:subject:subject:to:to; s=fm2; t=1725345689; x= 1725432089; bh=41Q0GRUnJbsINBQ2U9xz7m0gpKYR85KSmypXhPFA5Z0=; b=Z mLzaCU/9etYwKEV7OT32CKn1Dn45hKC9z2voIM8ZB6RIX0aB5WxFnX+qrmjQXQXJ S0God0eYNsnoYqY4TmsgKEMT7w2q2i/EGBO5DNsdNFZXjvtRRrmAHhBThCvMCCvz K+7+IVpeHITEKhZE2Old5AmbzXrtjxSmheErUqi/dRqKBsx9eO8X63nCAgprHwAn cvYLYpXyY2Eaqclu01tWJyKxYkoVyKeNexPJFluuGrZZog98jgE7h5gxZ5HbyuKn VVpB9u9AMEZgjoHhZttDreLTi7jpI3ZNjHtNC366R/Sp1baIpkskzYpSuj+4MNiy F2ndyHEjpwOOmTiXPQhdg== DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d= messagingengine.com; h=cc:cc:content-type:content-type:date:date :feedback-id:feedback-id:from:from:in-reply-to:in-reply-to :message-id:mime-version:references:reply-to:subject:subject:to :to:x-me-proxy:x-me-proxy:x-me-sender:x-me-sender:x-sasl-enc; s= fm1; t=1725345689; x=1725432089; bh=41Q0GRUnJbsINBQ2U9xz7m0gpKYR 85KSmypXhPFA5Z0=; b=U7hml1JYfwHs0xcKf/K9EZb9LcIhaTm4WP6mDZpBZ1s7 Bapejb9QTB9BbNzy/Q9vKB1/ug7b5RmMck2eH2niYo+u3uKrnVFrkS3HK8/WtIkn QcAZVWkOjMMOCRhrRAS5Ab9BfR7dMQKX8KPbVT+onmvr4qhHn/AZScMYxFE12Rb8 hgzmMfxVeSFZYCGHpZIdFk1/uM8J6Uj+wskbCXF446xkzTCkG9xZVxj0VNPLV24U S1WZPyjEMZ7ANxhvsYCsQKhe+mWuyI2AZXX5TN/x43z/bsvNt2BNyiBA83/Lfoo2 FFpWF3xrwuIUPQU6xbT4niVzY6FyIaThTWmyVZv8+A== X-ME-Sender: X-ME-Proxy-Cause: gggruggvucftvghtrhhoucdtuddrgeeftddrudehgedguddufecutefuodetggdotefrod ftvfcurfhrohhfihhlvgemucfhrghsthforghilhdpggftfghnshhusghstghrihgsvgdp uffrtefokffrpgfnqfghnecuuegrihhlohhuthemuceftddtnecuogfuuhhsphgvtghtff homhgrihhnucdlgeelmdenucfjughrpefoggffhffvvefkjghfufgtsegrtderreertdej necuhfhrohhmpedftfhosgcunfgrnhguvghrshdfuceorhhosgessghothhtlhgvugdrtg houggvsheqnecuggftrfgrthhtvghrnhepiefhueeuhfdutddthefgieeggeetjeejlefg ffeijeetkefhjeeujeefudegveehnecuffhomhgrihhnpeefvheglhdrohhrghdpghhith hhuhgsrdgtohhmnecuvehluhhsthgvrhfuihiivgeptdenucfrrghrrghmpehmrghilhhf rhhomheprhhosgessghothhtlhgvugdrtghouggvshdpnhgspghrtghpthhtohepvddpmh houggvpehsmhhtphhouhhtpdhrtghpthhtohephhgrmhhivghgohhlugesghhmrghilhdr tghomhdprhgtphhtthhopehinhhtvghrnhgrlhhssehlihhsthhsrdhphhhprdhnvght X-ME-Proxy: Feedback-ID: ifab94697:Fastmail Received: by mailuser.nyi.internal (Postfix, from userid 501) id E1D69780067; Tue, 3 Sep 2024 02:41:28 -0400 (EDT) X-Mailer: MessagingEngine.com Webmail Interface Precedence: bulk list-help: list-post: List-Id: internals.lists.php.net x-ms-reactions: disallow MIME-Version: 1.0 Date: Tue, 03 Sep 2024 08:41:08 +0200 To: "Hammed Ajao" Cc: internals@lists.php.net Message-ID: In-Reply-To: References: <0418049b-7981-40a0-a0f9-2430eceb7d12@app.fastmail.com> Subject: Re: [PHP-DEV] Pre-RFC Discussion: Support for String Literals as Object Properties and Named Parameters in PHP Content-Type: multipart/alternative; boundary=653a85e70c5240919c5dd009683b4aa9 From: rob@bottled.codes ("Rob Landers") --653a85e70c5240919c5dd009683b4aa9 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable On Tue, Sep 3, 2024, at 02:00, Hammed Ajao wrote: >=20 >=20 > On Mon, Sep 2, 2024 at 1:50=E2=80=AFPM Rob Landers = wrote: >> __ >> On Sun, Sep 1, 2024, at 23:47, Hammed Ajao wrote: >>> Dear PHP internals community, >>> I hope this email finds you all well. I'd like to propose an idea th= at I believe could enhance PHP's flexibility and consistency, especially= when working with string literals. I'm looking forward to hearing your = thoughts and feedback on this proposal. >>> Introduction >>> I'm suggesting two enhancements to PHP that I think could make our l= ives as developers a bit easier: >>>=20 >>> Support for String Literals as Object Properties >>> Support for String Literals as Named Parameters in Function Calls >>>=20 >>> The main goal here is to reduce our reliance on arrays and provide m= ore intuitive ways to define and access data, particularly in scenarios = like working with HTTP headers where we often deal with non-standard cha= racters and strings. >>> 1. String Literals as Object Properties >>> Current Situation >>> As we all know, we typically define and access object properties usi= ng standard identifiers: >>> ```php >>> class Foo { >>> public string $contentType =3D "application/json"; >>> } >>>=20 >>> $obj =3D new Foo(); >>> $obj->contentType =3D "text/html"; >>> ``` >>>=20 >>> But when we're dealing with data that includes non-standard characte= rs or strings (think HTTP headers), we often end up using associative ar= rays: >>> ```php >>> $headers =3D [ >>> "Content-Type" =3D> "application/json", >>> "X-Custom-Header" =3D> "value" >>> ]; >>> ``` >>>=20 >>> I think we can all agree that this reliance on arrays can make our c= ode less intuitive, especially when we're managing complex data structur= es. >>> Proposed Enhancement >>> What if we could use string literals as object property names? Here'= s what I'm thinking: >>> ```php >>> class MyHeaders { >>>=20 >>> public function __construct( >>> public string "Content-Type" =3D "application/json", >>> public string "Cache-Control" =3D "no-cache, no-store, must-= revalidate", >>> public string "Pragma" =3D "no-cache", >>> public string "Expires" =3D "0", >>> public string "X-Frame-Options" =3D "SAMEORIGIN", >>> public string "X-XSS-Protection" =3D "1; mode=3Dblock", >>> public string "X-Content-Type-Options" =3D "nosniff", >>> public string "Referrer-Policy" =3D "strict-origin-when-cros= s-origin", >>> public string "Access-Control-Allow-Origin" =3D "*", >>> public string "X-Custom-Header" =3D "value", >>> ) {} >>>=20 >>> public static function create(string ...$headers): self { >>> return new self(...$headers); // Throws an error if an unkno= wn named parameter is passed >>> } >>>=20 >>> public function dispatch(): void { >>> foreach ((array) $this as $name =3D> $value) { >>> header("$name: $value"); >>> } >>> } >>> } >>>=20 >>> $headers =3D new MyHeaders("Content-Type": "application/json", "X-Cu= stom-Header": "value"); >>> // or >>> $headers =3D MyHeaders::create("Content-Type": "text/html; charset=3D= utf-8", "X-Custom-Header": "value"); >>> $headers->dispatch(); >>> ``` >>> This would allow us to include characters in property names that are= n't typically allowed in PHP identifiers, like hyphens or spaces. I thin= k this could make our code more readable and aligned with natural data r= epresentation. >>> Benefits >>>=20 >>> Greater Flexibility: We could create more natural and direct represe= ntations of data within objects. >>> Enhanced Consistency: This aligns with the proposed support for stri= ng literals as named parameters, creating a more uniform language experi= ence. >>> Simplification: It could reduce our need for associative arrays, whi= ch can be more error-prone and less intuitive. >>>=20 >>> 2. String Literals as Named Parameters in Function Calls >>> If we're going to use string literals as object properties, it makes= sense to also use them as named parameters, especially in constructors = with promoted properties. And why stop at constructors? This leads to th= e second part of my proposal. >>> Current Situation >>> We can use named parameters in function calls, but only with standar= d identifiers: >>> ```php >>> function myHeaders(...$args) { >>> foreach ($args as $key =3D> $value) header("$key: $value"); >>> } >>> ``` >>>=20 >>> To use string literals with special characters, we have to use assoc= iative arrays: >>> ```php >>> myHeaders(...["Content-Type" =3D> "application/json"]); >>> ``` >>>=20 >>> This can be a bit cumbersome and less readable, especially for compl= ex data structures. >>> Proposed Enhancement >>> What if we could use string literals as named parameters? It might l= ook something like this: >>> ```php >>> foo("Content-Type": "application/json"); >>> ``` >>>=20 >>> I think this syntax could offer several advantages: >>>=20 >>> Improved Readability: Our code could become clearer and more aligned= with natural data representation. >>> Automatic Parameter Mapping: We could map string literals to corresp= onding parameters without requiring manual intervention. >>> Simplified Constructor Usage: This could be especially beneficial fo= r constructors where we need to pass complex data structures directly. >>>=20 >>> Implementation Considerations >>> Of course, implementing these changes would require some work: >>>=20 >>> The PHP engine would need to accommodate string literals as valid pr= operty names and named parameters, both at runtime and in class/function= definitions. >>> We'd need to carefully manage compatibility with existing code to en= sure traditional property access remains unaffected. >>> We'd need to decide whether to allow string literals as parameters i= n function/method declarations or only in function calls (to be retrieve= d by func_get_args() or variadic functions), with exceptions for constru= ctors with promoted properties. >>>=20 >>> I'm really interested to hear what you all think about this proposal= . Do you see potential benefits or challenges that I might have overlook= ed? How do you think this could impact your day-to-day coding? >>> Looking forward to a great discussion! >>> Best regards, >>> Hammed >>=20 >> Hey Hammed, >>=20 >> This gets into the parser and its definition of "LABEL" (below PHP's = syntax): >>=20 >> LABEL [a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]* >>=20 >> This means the first letter must be alpha-numeric ascii, or higher. A= nd you can actually just use the latter part and whatever encoding your = file is (usually utf8): >>=20 >> For example, this is valid PHP: >>=20 >> class HTML { >> public string $Content=E2=80=93Type; >> public string $=E1=8B=90xl; >> public string $=F0=9D=9F=B70sm; >> } >>=20 >> https://3v4l.org/KgJKm >>=20 >> You can also use emojis or look-alikes as much as you want. It's not = a direct answer to what you are seeking, but it gets pretty close. >>=20 >> =E2=80=94 Rob > Hi Rob, >=20 > That's actually pretty neat, but it starts to fall apart when you need= the unicode representation e.g. converting to json :https://3v4l.org/VX= fDl . >=20 > Hammed Hey Hammed, You'll still need to do a conversion of some type; luckily, someone else= maintains a list: https://github.com/codebox/homoglyph/blob/master/raw_= data/chars.txt I briefly looked into allowing this last night and allowing properties l= ike this would allow everything to have a full string representation. Th= is would be valid: $"fancy-thing" =3D other fancy thing. The thing is, we kinda already allow it through variable-variables and o= ther means, as this is all valid php: https://3v4l.org/nFBeV So, if I understand correctly, you are seeking a syntax to allow for def= ining the properties without using dynamic properties? Currently, you can access the property like this: $this->{'my-invalid-prop'} So, why not embrace what already exists instead of trying to change the = syntax drastically? So, like this, maybe? public string {'my-invalid-prop'}; Allowing this appears to be on the grammar level of the language, meanin= g it is probably a straightforward change. =E2=80=94 Rob --653a85e70c5240919c5dd009683b4aa9 Content-Type: text/html; charset=utf-8 Content-Transfer-Encoding: quoted-printable
On Tue, Sep 3, = 2024, at 02:00, Hammed Ajao wrote:


=
On Mon, Sep 2, 2024 at 1:50=E2=80=AFPM Rob Landers <rob@bottled.= codes> wrote:

On Sun, Sep 1, 2024, at 23:47, Hammed Ajao w= rote:
Dear PHP internals community,
I = hope this email finds you all well. I'd like to propose an idea that I b= elieve could enhance PHP's flexibility and consistency, especially when = working with string literals. I'm looking forward to hearing your though= ts and feedback on this proposal.
Introduction
I'm suggesting two enhancements to PHP that I think could make our li= ves as developers a bit easier:

Support for= String Literals as Object Properties
Support for String L= iterals as Named Parameters in Function Calls

The main goal here is to reduce our reliance on arrays and provide mo= re intuitive ways to define and access data, particularly in scenarios l= ike working with HTTP headers where we often deal with non-standard char= acters and strings.
1. String Literals as Object Propertie= s
Current Situation
As we all know, we typic= ally define and access object properties using standard identifiers:
=
```php
class Foo {
    = public string $contentType =3D "application/json";
}

$obj =3D new Foo();
$obj->conte= ntType =3D "text/html";
```

B= ut when we're dealing with data that includes non-standard characters or= strings (think HTTP headers), we often end up using associative arrays:=
```php
$headers =3D [
  =   "Content-Type" =3D> "application/json",
  &= nbsp; "X-Custom-Header" =3D> "value"
];
`= ``

I think we can all agree that this relia= nce on arrays can make our code less intuitive, especially when we're ma= naging complex data structures.
Proposed Enhancement
What if we could use string literals as object property names? = Here's what I'm thinking:
```php
class MyHea= ders {

    public function __cons= truct(
        public string "Content-= Type" =3D "application/json",
        = public string "Cache-Control" =3D "no-cache, no-store, must-revalidate",=
        public string "Pragma" =3D "n= o-cache",
        public string "Expir= es" =3D "0",
        public string "X-= Frame-Options" =3D "SAMEORIGIN",
      &nbs= p; public string "X-XSS-Protection" =3D "1; mode=3Dblock",
        public string "X-Content-Type-Options" =3D = "nosniff",
        public string "Refe= rrer-Policy" =3D "strict-origin-when-cross-origin",
 =       public string "Access-Control-Allow-Origin" =3D "*= ",
        public string "X-Custom-Hea= der" =3D "value",
    ) {}

    public static function create(string ...$headers):= self {
        return new self(...$he= aders); // Throws an error if an unknown named parameter is passed
    }

    publ= ic function dispatch(): void {
       = foreach ((array) $this as $name =3D> $value) {
  =           header("$name: $value");
        }
    }
<= div>}

$headers =3D new MyHeaders("Content-T= ype": "application/json", "X-Custom-Header": "value");
// = or
$headers =3D MyHeaders::create("Content-Type": "text/ht= ml; charset=3Dutf-8", "X-Custom-Header": "value");
$header= s->dispatch();
```
This would allow us to= include characters in property names that aren't typically allowed in P= HP identifiers, like hyphens or spaces. I think this could make our code= more readable and aligned with natural data representation.
Benefits

Greater Flexibility: We could c= reate more natural and direct representations of data within objects.
Enhanced Consistency: This aligns with the proposed support = for string literals as named parameters, creating a more uniform languag= e experience.
Simplification: It could reduce our need for= associative arrays, which can be more error-prone and less intuitive.

2. String Literals as Named Parameters in Fu= nction Calls
If we're going to use string literals as obje= ct properties, it makes sense to also use them as named parameters, espe= cially in constructors with promoted properties. And why stop at constru= ctors? This leads to the second part of my proposal.
Curre= nt Situation
We can use named parameters in function calls= , but only with standard identifiers:
```php
function myHeaders(...$args) {
    foreach ($ar= gs as $key =3D> $value) header("$key: $value");
}
```

To use string literals with sp= ecial characters, we have to use associative arrays:
```ph= p
myHeaders(...["Content-Type" =3D> "application/json"]= );
```

This can be a bit cumb= ersome and less readable, especially for complex data structures.
Proposed Enhancement
What if we could use string l= iterals as named parameters? It might look something like this:
```php
foo("Content-Type": "application/json");
<= /div>
```

I think this syntax could off= er several advantages:

Improved Readability= : Our code could become clearer and more aligned with natural data repre= sentation.
Automatic Parameter Mapping: We could map strin= g literals to corresponding parameters without requiring manual interven= tion.
Simplified Constructor Usage: This could be especial= ly beneficial for constructors where we need to pass complex data struct= ures directly.

Implementation Consideration= s
Of course, implementing these changes would require some= work:

The PHP engine would need to accommo= date string literals as valid property names and named parameters, both = at runtime and in class/function definitions.
We'd need to= carefully manage compatibility with existing code to ensure traditional= property access remains unaffected.
We'd need to decide w= hether to allow string literals as parameters in function/method declara= tions or only in function calls (to be retrieved by func_get_args() or v= ariadic functions), with exceptions for constructors with promoted prope= rties.

I'm really interested to hear what y= ou all think about this proposal. Do you see potential benefits or chall= enges that I might have overlooked? How do you think this could impact y= our day-to-day coding?
Looking forward to a great discussi= on!
Best regards,
Hammed

Hey Hammed,

Th= is gets into the parser and its definition of "LABEL" (below PHP's synta= x):

LABEL [a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80= -\xff]*

This means the first letter must be= alpha-numeric ascii, or higher. And you can actually just use the latte= r part and whatever encoding your file is (usually utf8):
=
For example, this is valid PHP:

<= div>class HTML {
    public string $Content= =E2=80=93Type;
    public string $=E1=8B=90= xl;
    public string $=F0=9D=9F=B70sm;
=
}


You can also use emojis or look-alikes as much as you want. It's = not a direct answer to what you are seeking, but it gets pretty close.

=E2=80=94 Rob
Hi Rob,
<= div>
That's actually pretty neat, but it starts to fall ap= art when you need the unicode representation e.g. converting to json :https://3v4l.org/VXfDl .
<= div>
Hammed

Hey Hammed,

You'll still need to do a c= onversion of some type; luckily, someone else maintains a list: https://github.com/codebox/homoglyph/blob/master/raw_data/chars.txt=

I briefly looked into allowing this la= st night and allowing properties like this would allow everything to hav= e a full string representation. This would be valid:

<= /div>
$"fancy-thing" =3D other fancy thing.

=
The thing is, we kinda already allow it through variable-variables = and other means, as this is all valid php: https://3v4l.org/nFBeV

So, i= f I understand correctly, you are seeking a syntax to allow for defining= the properties without using dynamic properties?

Currently, you can access the property like this:
<= br>
$this->{'my-invalid-prop'}

So, why not embrace what already exists instead of trying to change the= syntax drastically? So, like this, maybe?

= public string {'my-invalid-prop'};

Allowing= this appears to be on the grammar level of the language, meaning it is = probably a straightforward change.

=E2=80=94 Rob
--653a85e70c5240919c5dd009683b4aa9--