Re: [Discussion] Why can't I do "{$a::class}"?
| From: | Robert Landers | Date: | Sun, 19 May 2024 10:39:29 +0000 |
| Subject: | Re: [Discussion] Why can't I do "{$a::class}"? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-123365@lists.php.net to get a copy of this message | ||
On Sun, May 19, 2024 at 10:33 AM Peter Stalman <sarkedev@gmail.com> wrote:
>
> Hi Internals,
>
> Obviously we can't use constants or functions directly in strings using variable parsing,
> I assume because it lacks the easily detectable $.
>
> However, we _can_ use methods because the object variable has the $, which I assume is the
> reason methods work and functions don't.
>
> I feel like it's something that _could_ have been added when dynamic access of static
> members support was added in 5.3.0, but maybe it was overlooked or decided against? Consider:
>
> ```
> <?php
>
> $a = new A();
>
> echo " {A::$static_property} \n"; // doesn't work (unless $static_property is a
> variable)
> echo " {$a::$static_property} \n"; // works
>
> echo " {A::static_method()} \n"; // doesn't work (just text)
> echo " {$a::static_method()} \n"; // works
>
> echo " {A::constant} \n"; // doesn't work
> echo " {$a::constant} \n"; // doesn't work either, but why?
>
> ?>
> ```
>
>
> Also, as a side note, why does this hack below work? It seems like something that would use
>
eval(), but doesn't. Take a look:
>
> https://3v4l.org/aPCSD
>
> I found it at the bottom of the manual entry for Strings[1]. Not something I would use, but
> it's interesting to see.
>
> Thanks,
> Peter
>
> [1]:
> https://www.php.net/manual/en/language.types.string.php#91628
In general, it would be nice to have some proper inline string
templating, like other languages (js, C#, etc). At least some way to
evaluate an expression and format. I'm thinking like in C#:
$"Price: {price:C2}, Quantity: {quantity}, Discount: {discount:P1},
Total after discount: {(price * quantity * (1 - discount)):N2}"
Price is formatted using currency with 2 decimal places, discount is
formatted using percentage and one decimal, and N is a number format
with 2 decimals.
Robert Landers
Software Engineer
Utrecht NL