Re: [PHP-DEV] Compact can't resolve outer scoped variables using short closures

2022-10-20 Thread David Rodrigues
> $foo = fn() => [$a, compact('a', 'b')];
> is essentially compiled to:
> $foo = function (use $a) { return [$a, compact('a', 'b')] };

Regarding this, in case you're literally saying that internally "fn()"
turns into a common "function", and getting back to the main topic, would
it be possible to do the same with compact()?

fn() => compact('dummy')
turns into:
fn() => [ 'dummy' => $dummy ]
which turns into:
function() use($dummy) { return [ 'dummy' => $dummy ]; }




Atenciosamente,
David Rodrigues


Re: [PHP-DEV] Compact can't resolve outer scoped variables using short closures

2022-10-19 Thread David Rodrigues
> I'd rather hope for `compact()` to finally be deprecated and targeted for
removal 😛

I think compact() is a good function for transferring variables from one
point to another, but I would think about making improvements as it is
confusing (uses the variable name, rather than the variable itself).

Regarding the bug, if we use an array it should work perfectly:

$x = 123;
(fn() => [ 'x' => $x ])();

https://3v4l.org/ov7TM

Would it be possible to automatically convert compact() to an array at
runtime? So I imagine that any necessary optimization can take place
directly over the resulting array, rather than the compact itself.


Atenciosamente,
David Rodrigues


Em qua., 19 de out. de 2022 às 14:09, Marco Pivetta 
escreveu:

> On Wed, 19 Oct 2022, 19:04 David Rodrigues, 
> wrote:
>
>> Hello!
>>
>> I'm converting my code to use short closures where possible, and I ran
>> into
>> a problem using compact().
>>
>> Basically, the names used in compact() cannot be accessed due to a bug,
>> reported in 2019 still in PHP 7.4 (ID 78970).
>>
>> https://bugs.php.net/bug.php?id=78970
>>
>> It seems to me to be a reasonable problem and one that needs attention, as
>> the message is not that "compact cannot be used here", but that "the
>> variable does not exist".
>>
>> The code below may reproduce the problem:
>>
>> $x = 123;
>> (fn() => compact('x'))();
>>
>> https://3v4l.org/AFARs
>>
>> Is there any possibility of this being fixed? I would love to help, but I
>> don't have much C programming skills, unfortunately.
>>
>
> I'd rather hope for `compact()` to finally be deprecated and targeted for
> removal 😛
>
> The fact that it still exists precludes (or at least complicates) future
> optimization of scope + inlining in the engine.
>
> Similar thoughts towards `extract()`, I'd say.
>
>


[PHP-DEV] Compact can't resolve outer scoped variables using short closures

2022-10-19 Thread David Rodrigues
Hello!

I'm converting my code to use short closures where possible, and I ran into
a problem using compact().

Basically, the names used in compact() cannot be accessed due to a bug,
reported in 2019 still in PHP 7.4 (ID 78970).

https://bugs.php.net/bug.php?id=78970

It seems to me to be a reasonable problem and one that needs attention, as
the message is not that "compact cannot be used here", but that "the
variable does not exist".

The code below may reproduce the problem:

$x = 123;
(fn() => compact('x'))();

https://3v4l.org/AFARs

Is there any possibility of this being fixed? I would love to help, but I
don't have much C programming skills, unfortunately.


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] [RFC] Destructuring Coalesce

2022-10-16 Thread David Rodrigues
I like it!

But what should happen if:

[ $a ?? '123', $b ] = [];
[ $a ?? '123', $b ] = [ 1 ];
[ $a ?? '123', $b ] = [ 1, 2 ];

It also supports ?: operator?

[ $a ?: '123' ] = []; so $a = '123'
[ $a ?: '123' ] = [ false ]; so $a = '123'
[ $a ?: '123' ] = [ 456 ]; so $a = 456


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] Feature preview (formely was: experimental features)

2022-10-11 Thread David Rodrigues
>From what I understand, your concern is "what if we need to change the
direction of something already decided"? For example, initially it was
decided and very well accepted private(set), but after a while the idea was
revised and it was decided that private:set would be better instead.

In this case, I still believe that the ideal is that this does not change.
But we have a options to decide:

(1) Do not allow changes of this type, as private(set) was initially well
accepted and, unfortunately, nothing can be done. Perhaps, with the
exception of code conflicts that might be discovered later.

(2) Allow BC if the change is reasonable (in this example, if some sort of
code conflict is later discovered). AND:
(2.a) Keep the old syntax (private(set)) at least until the official
version is released, which will use private:set if possible.
(2.b) Keep the old syntax for at least a few releases (eg. patch+3), or a
few months (eg. 6 months) if possible.
(2.c) Consider BC permanent and users will need to change existing codes
immediately.

In particular, I believe that option (1) is ideal, or in the last case
(2.a). While option (2.c) would be easier to maintain and also acceptable,
as users using preview features will be using it at the risk of things like
this happening.

In general, the proposal is to allow new features to be tested more easily
and earlier, as long as they are ready for use and in their final version
(or very close to it). Something like a "Release Candidate" version of this
new feature.



(By top posting, you mean what gmail does by keeping the previous message
at the end of the email, right? I'll be more careful, thanks!)


Re: [PHP-DEV] Feature preview (formely was: experimental features)

2022-10-11 Thread David Rodrigues
Nice example!

> You're saying that "public private(set)" would become available in 8.2.1
(the late-December release of 8.2), but only in files that have
"declare(asymmetric_visibility=1);" at the top.

Yes. In that case, I should suggest declare(preview_asymmetric_visibility =
1), just to make clear that it is using a preview feature.

> However, we could still change the syntax from "public private(set)" to
"public private:set" in 8.2.6 if we decided to; that wouldn't be considered
a BC break.  But once we get to 8.3.0, whatever the syntax is at that point
is frozen and no longer changeable, and available in all files. The
declare() is now irrelevant.

Partially. As the usage definition has not yet been decided between
private(set) vs. private:set, so this feature is not ready for preview.
Unless the idea of allowing the two syntaxes to co-exist in this feature is
acceptable (which I personally think is a bad idea).


Atenciosamente,
David Rodrigues


Em ter., 11 de out. de 2022 às 22:23, Larry Garfield 
escreveu:

> On Tue, Oct 11, 2022, at 3:25 PM, David Rodrigues wrote:
> > In order to try to organize a little better the original purpose of the
> > discussion I started, I decided to "rename" this subject to something
> > closer to the purpose. From "experimental features" to "feature preview".
> >
> > Original thread: https://marc.info/?l=php-internals&m=166491585711553
> >
> > These are my suggestions, as per the discussion that took place during
> the
> > original thread.
> >
> > (A) What are preview features:
> >
> > (A1) There are features ALREADY 100% APPROVED through the voting system
> > among the PHP team and that can already be implemented in the language
> in a
> > preview format (via PR), available to the general public through
> > minor/patch releases through "preview" markers.
> >
> > (A2) These are features that are understood to be effective for the
> > language and that will be available in a future major (eg. 9.0) or minor
> > release (eg. 8.2). That is, it is not intended to be removed "at any
> time".
> >
> > (B) What are NOT preview features:
> >
> > (B1) Suggested features, even if well accepted during discussions, but
> not
> > passed the voting process as approved, even if a PR is already available.
> >
> > (B2) Experimental features (literal), whose idea would be to test "in
> > practice" its functionality before deciding if it will be part of the
> > language or not.
> >
> > (B3) Features that may have a high risk of rejection due to performance,
> > security or usability issues, even if they were approved during
> > voting. That is: when in doubt, even if approved, keep it as exclusive to
> > the next release.
> >
> > (B4) New features approved but with pending discussion should not be
> > previewable. For example: json_validate() is approved, but the function
> > name is under discussion whether is_json_valid() or json_validate() is
> > better. In this case, it prefers to keep it out of the preview until that
> > is decided.
> >
> > (C) What changes in the voting process:
> >
> > (C1) An additional voting topic to decide whether a new feature can be
> > previewed or not (i.e. basically deciding whether the feature is safe to
> > test ahead of time, taking security primarily into account).
> >
> > (C2) Additionally, decide what the target version of PHP will be (eg. PHP
> > 8.2? 8.3? 9.0?). This helps more complex features get more preview and
> > feedback time.
> >
> > (D) Advantages:
> >
> > (D1) New features will be able to be tested before an official release
> (eg.
> > 8.2), and all issues can be resolved before this release.
> >
> > (D2) During the voting process, a feature can be developed for the next
> > version (eg. 8.2) or postponed to the next-next version (eg. 8.3), if it
> > encounters difficulties, without freezing/delaying the release of version
> > 8.2, for example.
> >
> > (D3) Regular users will be able to test features in preview, without
> > installing nothing (eg. PECL), since they will be available natively in
> > PHP. Of course, with the notion of the impacts such features can have
> (like
> > needing to use markers, minimal performance issues). It is important that
> > the documentation makes it clear that a particular feature is under
> > development in preview mode.
> >
> > (D4) The development team will have early feedback on these features, and
> > will be able to work on fixes with more "pea

[PHP-DEV] Feature preview (formely was: experimental features)

2022-10-11 Thread David Rodrigues
't
think there is any approved, but eventually we will), for example, and make
it available in PHP 8.2 as preview. So we test in practice whether the idea
itself will work or not (and even user adherence, with open source projects
and feedback). And if all goes well, we can make it default for PHP to
offer this kind of support. If something goes wrong, we can let this idea
go.

(F5) Preview features should generally be released in patch versions (eg.
PHP 8.1.12 to preview a PHP 8.2 feature).



Atenciosamente,
David Rodrigues


Re: [PHP-DEV] Experimental features

2022-10-10 Thread David Rodrigues
The idea is that the experimental features are exclusively something that
the PHP team has voted for (approved) and that will be part of the language.

Users can choose to install PECL, but it is not the same, because it
depends on other users (who can make use of this code) having the notion
that a certain PECL will be necessary.

Imagine a package under development (eg. Laravel 10) that is (supposing
that) intended to be released compatible with PHP 8.3 (supposing that it
already has experimental features). In this case, the Laravel team can
start using an experimental feature while developing Laravel 10, waiting
for the release of PHP 8.3. Once the PHP 8.3 release is finished, Laravel
10 can just remove the experimental tags and release its new version fastly.

The user, on condition that he is willing to use Laravel 10 (in
development) will make indirect use of experimental features. Then both the
Laravel team and these users will be able to provide feedback for these
features to the PHP team before the official release.

Like json_validate(): assuming Laravel needs to check if a code is valid
JSON, but without processing its data for use. It could check if PHP >=
8.3, so use experimental_json_validate(), else use previous PHP compatible
code.


Atenciosamente,
David Rodrigues


Em seg., 10 de out. de 2022 às 19:20, David Gebler 
escreveu:

> My two cents...
>
> Why can't "common users" install a PECL extension? It's not a difficult,
> obscure or undocumented process.
>
> I can accept the reasoning
>
> > Apply a PECL strategy to try experimental features might not be the
> convenient way always, for example, if we create a new ... sensitive ini
> setting that affects the behavior of PHP somehow... OR ... what about a new
> sensitive funtion in a "core extension" like JSON?
>
> But why would the answer in those cases not be "compile the PHP
> fork/branch with the experimental feature", rather than find a way to flag
> the engine to switch arbitrary new features on or off, complete with all
> the complications in the primary source code that would cause? We are,
> after all, talking about features which by definition should not be relied
> upon for any production use.
>
> Or we're talking about features which are stable and valuable enough to
> have passed an RFC process, but then what's gained from an experimental
> designation? Why couldn't they just be included in a preview/beta/RC
> version which anyone could decide to run or not?
>


Re: [PHP-DEV] Experimental features

2022-10-06 Thread David Rodrigues
> If I start coding an application that relies on these new types, is there
a chance that they'll be removed completely, and I have to rewrite it all?

Imagine that there are users, like me, who would like to test features in
development (mainly in order to provide feedback to the development team).
It shouldn't be something a user should use for big productions, but maybe
for smaller personal projects.

This is an opportunity to make improvements to the feature for the next
release, without the risk of having to do so during it.

But keep in mind that these features are already intended for PHP, and it
is not a "feature test" or suggestion. The voting process is mandatory and
the feature must already be set to "accepted".

However, we need to separate an experimental feature into stages, much like
Node does, so these are my suggestions:

1. Closed experimental: the feature has successfully passed the approval
phase, including an available PR. However, the feature will only be
available through additional configuration in php.ini, as it can still
undergo BC changes, including its complete removal.

2. Open experimental: the feature has already been state internally by
"adventurous users" and can already be used without php.ini configurations,
however, its use in code still needs experimental markers (eg.
experimental_json_validate() or declare(experimental_*)). BC is unlikely to
happen unless the feature has issues that need to be resolved before an
official release. Removing the feature is suggested not to happen, with the
exception of very serious and irreparable issues.

3. Stable: the feature proves stable enough to be used "as is" in an
official version, but is still kept as an experimental marker until a new
official version is released. At this point, imagine that it is as if the
resource were indeed official, so it would no longer be possible to remove
it or make BC changes.

4. Available: the feature is now an official part of the language and can
be used in a major/minor version without the experimental markers. Markers
will continue to work until the next major update as an alias.

Also, if a user tries to use experimental features without being aware of
it (eg. did not activate it in php.ini or did not use declare()), an error
message should be displayed.

It also makes me rethink the time it takes for a feature to be ready to be
officially delivered. My suggestion would be at least 3 months for the 1st
and another 3 months for the 2nd stage. While the "stable" stage would last
as long as needed for the next major/minor release.

This generates less risk for new features and earlier feedback from users
willing to test it.

Atenciosamente,
David Rodrigues


Em qui., 6 de out. de 2022 às 17:12, Rowan Tommins 
escreveu:

> On 06/10/2022 17:41, Alex Wells wrote:
> > For example, Kotlin has recently introduced a new feature - unsigned
> integer types.
>
>
> I'm still struggling to understand what I, as a user, would do about this.
>
> If I start coding an application that relies on these new types, is
> there a chance that they'll be removed completely, and I have to rewrite
> it all? Is there a chance that every minor version I upgrade might
> introduce subtle changes in the behaviour of my code? Or is there just a
> chance that someone will decide the bikeshed's the wrong colour and I
> have to regex replace all my "123u" to say "u123" instead?
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Experimental features

2022-10-05 Thread David Rodrigues
Thank you all for participating in this discussion!

Regarding the experimental features "disappearing" in a release, therefore,
its use is not reliable, in reality the idea is that this is the exception
of the exception (when, for example, the feature itself proves to be
extremely unfeasible for performance or generating irreparable security
flaws). It is not something as if every new idea becomes an experimental
feature, but rather, ideas that already had a good technical discussion and
the doubt was in the practical application itself, but with a great
intention of turning it native in the language, however, making it
available before time for refinement and common usage.

Regarding the code development, following the previous statement, the idea
is that the core developers work on these modifications as well, since the
idea of experimental features is for the code to become a native part of
PHP.

It's different from extensions, where the discussion is on the way to
rejection and the developer who suggested it intends to do something
practical aside, and eventually the PHP team decides to make it native (but
that's another discussion, and I believe it's already possible at the
moment, at least part of the idea).

A more practical example is the following:

In the PHP RFC we have several proposals already accepted, often before the
vote, we already have a good idea of their acceptance. But let's pay
attention to only those votes that have already been approved. Normally
these features are only applied in the next version, PHP 8.2, however, when
it is released, it may lack some refinements in this sense.

Let's take, for example, the RFC "allow null and false as stand-alone
types". This feature was voted and passed unanimously on 2022-03-27, but
PHP 8.2 is due for 2022-11-24 (as far as I know -- aka Google tells me).
However, it is a feature already developed and could very well be available
on an experimental basis, so we have time to test it on smaller or personal
projects, for example, until PHP 8.2 is available where this functionality
will be 100% refined and ready to use.

declare (experimental_allow_null_false_standalone_type = 1);

Another advantage in this sense is that it would be possible to have a
single development branch for PHP 8.1 (current version) and 8.2
(development version), for example, with the difference of some definitions
in the code that activate or deactivate the experimental features already
developed for the future version.

So a new intended feature can be developed in 8.1 code and marked as
experimental (and common users will be able to try them out, using them in
an experimentally explicit way), and when you start preparing for the 8.2
release, those definitions become final.

Another advantage is that a new feature can be "delayed" to a future-future
version (eg. 8.3) if it is believed not to be refined enough for the next
version's release.

All I want to say is: I would love to be able to use new PHP features ahead
of time in personal projects, without having to wait for new versions to be
released (and in the meantime, I would be able to give feedback). Just as
I'm willing to take the risk of failure, after all, these are experimental
features and shouldn't be used in production (unless you're willing to take
risks). The difference between using the in-development version of PHP 8.2
is that many servers only make this version officially available after a
few months, while smaller versions of PHP usually become available within a
few days.


Atenciosamente,
David Rodrigues


Em qua., 5 de out. de 2022 às 13:02, Christian Schneider <
cschn...@cschneid.com> escreveu:

> Am 05.10.2022 um 15:38 schrieb Alex Wells :
> > Advantages of experimental features over extensions:
> > - they allow changes to the parser
> > - they are universally supported (by IDE's, parsers etc) because they are
> > part of a stable language release, not an unpopular/unknown extension
> > - usages of them can be found in a codebase and then analysed (unlike
> > extensions that don't have any kind of marker to denote them from regular
> > code)
> > - it's easy to implement a universal warning mechanism - for IDEs, static
> > analysers and PHP itself to warn users about the consequences of using an
> > experimental feature
> > - they don't need a versioning mechanism, because they are effectively
> > always "alpha" - i.e. non-stable, so any PHP release can introduce a
> > breaking change into an experimental feature
>
> Just to maybe have a more complete picture, here are some possible
> advantages of extensions over experimental features;
> - Core developers don't have to support/maintain it (they already have a
> lot on their plate)
> - Extensions have the notion of alpha/beta/stable r

Re: [PHP-DEV] Experimental features

2022-10-04 Thread David Rodrigues
Hi Flávio and Hans!

> Could this be done through extensions instead of having to develop a new
process/support code?

I believe it is possible, however, the main part of the idea would be that
"common users" could try out the features without having to know how to
install extensions, while there is an explicit notion that the feature used
is experimental (via experimental_() prefix for functions or method, for
instance) and that the goal is to test it to become part of PHP itself at
some point, not more as an extension but as a native part. So if these
experimental extensions are available natively and enabled by default, it
would be interesting, because it would be easier to separate the main code
from the code in development/refinement (and that can be rejected at some
point in a more practical way, and maybe be kept as just an extension apart
from PHP).




Atenciosamente,
David Rodrigues


Em ter., 4 de out. de 2022 às 19:37, Flávio Heleno 
escreveu:

> On Tue, Oct 4, 2022, 17:43 David Rodrigues  wrote:
>
>> I wanted to suggest the possibility of introducing experimental features
>> to
>> PHP.
>>
>> This is an old thread I guess, but I think it's good to reevaluate the
>> situation from time to time, as other languages already do this to some
>> extent and PHP doesn't. Some platforms/languages (Node, Kotlin) and
>> libraries (React) bring features natively in an experimental way.
>>
>> I wanted to propose that we bring this idea into PHP, so we wouldn't have
>> to wait for new major/minor versions (eg. 9.0 or 8.2, 8.3) to try out
>> these
>> new features, and so when these versions arrive, they'll already be quite
>> polished, avoiding patches sometime later due to wider usage of users.
>>
>> My idea is to have two levels of experimental features:
>>
>> (1) Via declare(), when the feature affects how PHP can act when reading
>> the file itself. Eg. declare(experimental_operator_override =
>> true), Something that happens with Kotlin, for example, when we use some
>> experimental annotations like contracts. These declarations work "per
>> file", so whenever it is necessary to use it, it must be declared.
>>
>> (2) Via experimental identifier name. Eg. experimental_json_validate() or
>> Experimental::json_validate(), like in Kotlin and also in React.
>>
>> Experimental features can only be brought into a minor version (eg. PHP
>> 8.1.12) when it is minimally refined and practically ready to use. It
>> would
>> be "kind of" an expected final version, no new patches are expected (we
>> hope), unless something really went unnoticed.
>>
>> Despite this, experimental features may not exist until the next
>> major/minor release if its practical inefficiency is found or if the
>> concept is shown to be invalid. So it should always be a "use with care".
>>
>> However, if an experimental feature is successful, it becomes final at the
>> next major/minor or major/minor+1. The experimental version becomes an
>> alias during some future versions until it is removed entirely. This is
>> the
>> time for users to adapt their code and for IDEs to help us find them.
>>
>> With this, we can understand whether users are making use of a certain
>> feature or not, make improvements on it, etc.
>>
>> I notice that many good features are rejected because they are believed to
>> be bad for PHP or can be confusing, but without any practical testing.
>> Experimental features can make this analysis more grounded in practical
>> data than just possibilities.
>>
>> However, this also doesn't mean that any idea can become an experimental
>> feature, but ideas that have a good foundation and a good discussion
>> before
>> it. The difference is that the feature can be tested in practice before
>> being totally rejected, and approved features can be delivered ahead of
>> time to refine before the next version is released, allowing users to try
>> them out more easily.
>>
>>
>> Atenciosamente,
>> David Rodrigues
>>
>
> Hi David,
>
> Could this be done through extensions instead of having to develop a new
> process/support code?
>
> When json support was first introduced into php, it was done as an
> extension and then, after a while, incorporated into the core.
>
>
>


[PHP-DEV] Experimental features

2022-10-04 Thread David Rodrigues
I wanted to suggest the possibility of introducing experimental features to
PHP.

This is an old thread I guess, but I think it's good to reevaluate the
situation from time to time, as other languages already do this to some
extent and PHP doesn't. Some platforms/languages (Node, Kotlin) and
libraries (React) bring features natively in an experimental way.

I wanted to propose that we bring this idea into PHP, so we wouldn't have
to wait for new major/minor versions (eg. 9.0 or 8.2, 8.3) to try out these
new features, and so when these versions arrive, they'll already be quite
polished, avoiding patches sometime later due to wider usage of users.

My idea is to have two levels of experimental features:

(1) Via declare(), when the feature affects how PHP can act when reading
the file itself. Eg. declare(experimental_operator_override =
true), Something that happens with Kotlin, for example, when we use some
experimental annotations like contracts. These declarations work "per
file", so whenever it is necessary to use it, it must be declared.

(2) Via experimental identifier name. Eg. experimental_json_validate() or
Experimental::json_validate(), like in Kotlin and also in React.

Experimental features can only be brought into a minor version (eg. PHP
8.1.12) when it is minimally refined and practically ready to use. It would
be "kind of" an expected final version, no new patches are expected (we
hope), unless something really went unnoticed.

Despite this, experimental features may not exist until the next
major/minor release if its practical inefficiency is found or if the
concept is shown to be invalid. So it should always be a "use with care".

However, if an experimental feature is successful, it becomes final at the
next major/minor or major/minor+1. The experimental version becomes an
alias during some future versions until it is removed entirely. This is the
time for users to adapt their code and for IDEs to help us find them.

With this, we can understand whether users are making use of a certain
feature or not, make improvements on it, etc.

I notice that many good features are rejected because they are believed to
be bad for PHP or can be confusing, but without any practical testing.
Experimental features can make this analysis more grounded in practical
data than just possibilities.

However, this also doesn't mean that any idea can become an experimental
feature, but ideas that have a good foundation and a good discussion before
it. The difference is that the feature can be tested in practice before
being totally rejected, and approved features can be delivered ahead of
time to refine before the next version is released, allowing users to try
them out more easily.


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] array_merge() vs array unpacking performance

2022-08-01 Thread David Rodrigues
> There are already a number of optimizations in array_merge. It might
depend on the actual test data that you used. Maybe a specific path needs
to be optimized. Please provide some more details.

You are right. I do not know how I tested before, but actually,
array_merge() is bit faster than array unpacking.



Atenciosamente,
David Rodrigues


Em seg., 1 de ago. de 2022 às 14:45, Kamil Tekiela 
escreveu:

> Hi David,
>
> It would be useful if you could provide your measurements and the way you
> arrived at such results. A quick test doesn't seem to support your
> findings: https://3v4l.org/v5m9f#v8.1.8
>
> There are already a number of optimizations in array_merge. It might
> depend on the actual test data that you used. Maybe a specific path needs
> to be optimized. Please provide some more details.
>
> Regards,
> Kamil
>


[PHP-DEV] array_merge() vs array unpacking performance

2022-08-01 Thread David Rodrigues
Hello!

PHP 8.1 supports array unpacking with keys. I guess that is very similar to
array_merge(), but for some reason array_merge() is 50% slower than
unpacking.

So my question is: is there some way to optimize the engine so
array_merge() can work like unpacking?

Thanks!


Re: [PHP-DEV] RFC Idea - is_json - looking for feedback

2022-07-29 Thread David Rodrigues
I was about to say NO, but after being completely your argument, the idea
makes sense.

Initially I thought about using json_decode() with error capture, but the
idea that it would overload memory makes perfect sense, compared to a
simple structure analysis, if that is indeed the user's intention. The
performance would also be absurdly better.

What worries me above is the misuse of the function, like checking if
is_json() === true and using json_decode() right after. However, I believe
this can be easily optimized by the engine itself.

My vote is YES.


Atenciosamente,
David Rodrigues


Em sex., 29 de jul. de 2022 às 16:32, Michał Marcin Brzuchalski <
michal.brzuchal...@gmail.com> escreveu:

> Hi Juan,
>
> pt., 29 lip 2022, 16:26 użytkownik juan carlos morales <
> dev.juan.mora...@gmail.com> napisał:
>
> > I am following the RFC guideline for the first time. (
> > https://wiki.php.net/rfc/howto)
> >
> > As suggested there, I am here to get a feeling from you, regarding the
> > following RFC for PHP.
> >
> > # Change (draft):
> >
> > New function in php called like:
> >
> > is_json(string $string): bool
> >
> > ## Description
> > ### Parameters
> > string $string -> string to find out if is a valid JSON or not
> >
> > ### Return
> > Returns a bool. The function is capable to determine if the passed string
> > is a valid JSON (true) or not (false).
> >
> > # Why this function ?
> >
> > At the moment the only way to determine if a JSON-string is valid we have
> > to execute the json_decode() function.
> >
> > The drawback about this, is that json_decode() generates an in memory an
> > object/array (depending on parameters) while parsing the string; this
> leads
> > to a memory usage that is not needed (because we use memory for creating
> > the object/array) and also can cause an error for reaching the
> memory-limit
> > of the php process.
> >
>
> Personally I'd vote NO.
>
> Cheers,
> Michał Marcin Brzuchalski
>
> >
>


Re: [PHP-DEV] [RFC] Undefined Property Error Promotion

2022-04-15 Thread David Rodrigues
> $foo[?'maynotexist'] // returns null and emits no warning

In JS we have some like:

foo['maynotexist']
foo?.['maynotexist']

In PHP could be:

$foo['maynotexist']
$foo?->['maynotexist']

Atenciosamente,
David Rodrigues


Em sex., 15 de abr. de 2022 às 18:41, Mark Randall 
escreveu:

> On 06/04/2022 19:38, Larry Garfield wrote:
> > On the last point, regarding stdClass, I think the question is whether
> we want it to be consistent with classed object properties (throw) or with
> associative arrays (warnings).  stdClass is kind of an uncomfortable middle
> between those two.  I'm not sure which is better to align with, although I
> almost never use stdClass and tell others to avoid it as well so it doesn't
> really matter to me. :-)
>
>
> My preference is to treat it like any other property, but I am open to
> hearing additional comments on this.
>
> I'm not sure how much conversation we can expect on this one, if it
> remains quiet I intend to open the vote in a week or so.
>
> As a tangent, R11 has had some comments made about a better method for
> indicating which property / array keys are expected to be missing, such as:
>
> $foo[?'maynotexist'] // returns null and emits no warning
>
> Down the line this might allow us to fix up arrays as well, but that's a
> question for a different RFC.
>
> Mark Randall
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] [VOTE] Allow null and false as stand-alone types

2022-03-12 Thread David Rodrigues
Maybe I'm a little late to this discussion, but is there any reason why
*false|null* is allowed but *true|null* is not?

I can think of few cases where *true|null* could be interesting, but I've
been through situations like this.


Atenciosamente,
David Rodrigues


Em sáb., 12 de mar. de 2022 às 14:32, G. P. B. 
escreveu:

> I've started voting for the Allow null and false as stand-alone types RFC:
> https://wiki.php.net/rfc/null-false-standalone-types
>
> Voting will last for 2 weeks until 26th of March.
>
> Best regards,
>
> George P. Banyard
>


Re: [PHP-DEV] RFC Concept: "Import" of simplied string manipulation and other instructions from ASP Classic

2021-09-25 Thread David Rodrigues
Hello!

Why are the current date() alternatives not working for you?

- is_date() => checkdate(int $month, int $day, int $year) or
DateTime::createFromFormat('Y-m-d', $date) !== false;
- year() => date('Y');
- month() => date('m');
- day() => date('d');
- hour() => date('H');
- minute() => date('i');
- second() => date('s');
- week() => date('W');

I can agree with you that the current ways are a bit confusing for a
beginner. For example, I myself didn't know the representation of weeks
using date() -- I had to search. But I think creating new "root functions"
would be too much. Perhaps a package like Carbon could be very useful. Or
even the DateTime itself.


Atenciosamente,
David Rodrigues


Em sáb., 25 de set. de 2021 às 16:48, Daniele B via internals <
internals@lists.php.net> escreveu:

> Here we go with a list of Date and time functions:
> // Classic Aspfunction is_date(string $date) {}function year(?string
> $date) {}function month(?string $date) {}function day(?string $date)
> {}function hour(?string $date) {}function minute(?string $date) {}function
> second(?string $date) {}function weekday(?string $date) {}
> //other stuff to simplify:function date_add() {}
>
>
>
>  Original message 
> From: Kamil Tekiela 
> Date: 9/25/21  16:49  (GMT+01:00)
> To: daniele bonini 
> Cc: internals@lists.php.net
> Subject: Re: [PHP-DEV] RFC Concept: "Import" of simplied string
> manipulation and other instructions from ASP Classic
>
> Hi Daniele,
> Thanks for reaching out to internals. I am curious about your proposal.
> Could you please provide some examples of what you think was great in
> Classic ASP that you would like to see implemented in PHP? If you have
> implemented polyfills in PHP for them, could you share them with us?
> Regards,Kamil
>


[PHP-DEV] Class static initialization block

2021-09-11 Thread David Rodrigues
Hello!

I would like to suggest a feature I saw being implemented in the V8 9.4
engine called "*class static initialization block*".

https://v8.dev/blog/v8-release-94

In short, it is a method that is executed once when a class is imported and
loaded, allowing for some more advanced initialization process to be done.

class Test {
static readonly Carbon $now;

static () {
self::$now = now();
}
}

Currently I can only do this in a very hacky way, usually by creating a
public static method and calling it after class initialization.

class Test {
static Carbon $now;

public static function init(): void {
self::$now = now();
}
}

Test::init();

I think the way the V8 does is much more interesting.

Another alternative would be to create a magic method like __initialize().


[PHP-DEV] array_merge() inside looping optimization

2021-07-25 Thread David Rodrigues
Hi!

Using array_merge() inside a loop can greatly impact performance. From the
tests I did, doing it in the middle costs 250% more than doing it later:

- Inside: for(...) $x = array_merge($x, $y)
- After: for(...) $x[] = $y; array_merge(... $x)

Even using array_push() doesn't seem like a good alternative as it costs
140%.

https://pastebin.com/s7f4Ttm3
https://3v4l.org/Vqt7o (+83% for array_push(), +760% for array_merge()
inside)

As far as I know, the array_merge() function makes a copy of the array,
rather than updating the input array. It makes sense, but in some
situations, not so rare, it might be possible to optimize when the
destination variable is part of the argument.

$arr = array_merge($arr, [ 1, 2, 3 ]); // or
$arr = array_merge([ 1, 2, 3 ], $arr);

This could reduce processing cost and memory consumption, as it would no
longer be necessary to copy the array to generate another one.

Anyway, I don't know if this is actually possible, or if the cost-benefit
would be better than what there is today. But I believe it is a path to be
thought of.


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] Type casting syntax

2021-07-11 Thread David Rodrigues
I really like the casting syntax, but I think it is difficult to be
approved, at first, because there is already a "clearer" method for doing
something like that. Which for me, particularly, does not invalidate an
alternative.

My suggestion is to create a magic method like __cast(AllowedTypes $in):
self. Eg. __cast(string|int $in): BigNumber. Where AllowedTypes are the
classes allowed to be casted from (or "mixed").

So:

$bn = (BigNumber) '123';
$date = (Carbon) $date;
$timestamp = (Carbon) (int) $date;

I also wanted it to be possible to use a nullable cast, but the idea didn't
go forward (even though there were no alternatives). :(


Atenciosamente,
David Rodrigues


Em sáb., 10 de jul. de 2021 às 06:10, Max Semenik 
escreveu:

> I've been thinking about extending PHP's cast syntax to user-defined types,
> e.g. not only (int)$foo but also (MyClass)$foo. Currently, a T_STRING in
> parentheses is always treated as a constant - would it be acceptable to
> hijack this syntax when used in unary operation context, i.e. "(" T_STRING
> ")" expr? If not, any other alternatives?
>
> --
> Best regards,
> Max Semenik
>


Re: [PHP-DEV] [RFC] Add parse_query_string as an alternative to parse_str

2021-06-23 Thread David Rodrigues
I really prefer the Sara suggestion, instead of creating a new function
to do the same thing. parse_str($str): array.


Atenciosamente,
David Rodrigues


Em qua., 23 de jun. de 2021 às 20:20, Sara Golemon 
escreveu:

> On Wed, Jun 23, 2021 at 5:02 PM Kamil Tekiela 
> wrote:
>
> > I would like to propose a new simple RFC that aims to add a new function
> > called parse_query_string as an alternative to parse_str.
> >
> > https://wiki.php.net/rfc/parse_str_alternative
> >
> > The functionality stays the same, only the name and the way of returning
> > the array changes. While it is a rather insignificant change, I believe
> it
> > is one step closer to making PHP cleaner.
> >
> >
> There's a potential alternative option that doesn't require adding a new,
> parallel function.  We can use execute_data->return_value_used to figure
> out if parse_str() was called with the result assigned to a local var.
> This is overloady and probably a bad idea, but it's an option.
>
> if (ZEND_NUM_ARGS() == 2) {
>   // Put result into by-ref second arg
>   // parse_str($str, $refResult);
> } else if (EX(return_value_used)) {
>   // Put result into return_value
>   // $result = parse_str($str);
> } else {
>   // Put result into EG(local_symbol_table)
>   // parse_str($str);
>   php_error(E_DEPRECATED, ...);
> }
>
> Realistically, your approach is probably better simply because it doesn't
> depend on the assignment as a side-effect, and it'll be good to have a
> migration route, especially one which gives us a function with, frankly, a
> much better name.
>
> That said, and I'll sound like a broken record here, but this is another
> case of being something that can be sorted in userspace trivially:
>
> function parse_query_string(string $str): array {
>   parse_str($str, $ret);
>   return $ret;
> }
>
> Kinda +/- 0 on it at the moment.  I'm less hostile to it than
> str_contains()/str_left()/str_right()/etc...
>
> -Sara
>


[PHP-DEV] Method overload support

2021-04-25 Thread David Rodrigues
I know that this discussion comes back from time to time, but now that PHP
is quite strong in relation to argument typing, I think it is worthwhile to
have a quick discussion about it. Maybe to PHP 9.

One of the things I remember that was a big problem was the performance
impact in determining what the ideal method would be, without testing it
each time.

1. The test only needs to happen for overloaded methods. So, most of the
time, no change will occur.

2. Opcache may be able to help indicate which method will be executed, when
it is available. And perhaps, in some situations, it is possible to
determine which method will be tested as a priority, without having to test
all the time (in a loop, for example).

function printId(User $user) { return a($user->id); }
function printId(int $userId) { printf($userId); }

foreach ([1, 2, 3, 4, $userInstance] as $userId) {
printId($userId);
// First time:
// 1. Overload detected, but the best option is unknown;
// 2. Test option #1: rejected;
// 3. Test option #2: accepted and used;
// Next times:
// 1. Overload detected, the last occurrence was option #2, accepted
and used;
// 2. Option #2 can't be used for $userInstance, retest all options
(except #2).
}

3. Poorly typed functions or methods cannot be overloaded.

function printId(User $user) { ... }
function printId($user) { ... } // Fatal error


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] [VOTE] noreturn type

2021-04-03 Thread David Rodrigues
Just to spice up the discussion a bit, I will try to give my opinion on
this RFC...

It is very likely that the proposal will be accepted (it is already 33/10),
but I still find the terms "noreturn" or "never" unclear. "noreturn" are
two words together, and I am not particularly a fan of this type of
nomenclature (and it may sound repetitive and strange "return no return"),
while "never" can be ambiguous, it could be read as "never return" (OK) or
"return never" (and it sounds a little strange, I guess).

I saw someone (sorry, I don't remember who) suggesting the term "terminus",
so I thought of an alternative like "terminal". Or, if you still want to
take advantage of a keyword and without losing the meaning, "exit"
(including, it makes absolutely clear what is expected as "return": "return
the exit").

Is there any chance of discussing terms, even if the "never" indication is
winning at the moment? Or did I miss this discussion?

Thanks!


Atenciosamente,
David Rodrigues


Em sáb., 3 de abr. de 2021 às 23:07, Matthew Brown 
escreveu:

> On Sat, 3 Apr 2021 at 12:30, Benjamin Eberlei  wrote:
>
> >
> > But adding a new keyword "noreturn" would not be necessary, it could just
> > be an Attribute as i said in my first e-mail explaining my no-vote:
> >
> > #[NoReturn] // sets a function flag modifying the void behavior
> > public function foo(): nothing {
> > return; // throws if it reaches this point
> > }
> >
> > This would be closer to what Psalm and PHP-Stan use at the moment if we
> > replace nothing with void.
> >
> > The problem is that "void" is already not perfect, since the callside
> > doesn't care about "return null" with no return type vs "return" + void
> > return type.
> >
> > If we had "nothing" and "null" instead of "void", and we'd say like PHP
> > works, "return;" actually means "return null;", then:
> >
> > function foo(): nothing {
> > return; // Error: cannot return null from a function that returns
> > nothing.
> > }
> > function bar(): null {
> > return;
> > // or return null;
> > }
> >
> > This would more consistently tie into union types where |null is allowed,
> > however on its own it is not: "foo() : null => error".
> >
> > As Levi said, this noreturn/never just perpetuates/amplifies the existing
> > void mistake and feels off, given that other recent changes to PHP have
> > been more bold, towards removing inconsistencies.
> >
> >
> Clearly comparisons of "noreturn"/"never" to "void" are a bit of a
> minefield, because a number of contributors feel that void was a mistake,
> that its implementation doesn't feel PHP-like.
>
> While I disagree that our proposal is intrinsically connected with the void
> one – noreturn/never could work equally well with a "null" return — our
> proposal does perpetuate one idea behind "void": that PHP can benefit from
> types found in other languages and type systems, and especially types found
> in Hack.
>
> It seems like some of the debate is over whether "noreturn"/"never" is a
> behaviour or a type. If it were purely a behaviour, with no meaning as a
> type, an Attribute would be a much more appropriate location.
>
> It's not just a behaviour, though — it is a type that follows variance
> rules, and it's a type that PHP can check.
>
> If "void" returns are too much of a distraction, think instead of "object"
> return type declarations:
>
> When executing the function
>
> function returnsObject($o) : object {
> if (rand(0, 1)) {
> return $o;
> }
> }
>
> Here PHP's engine checks two separate behaviours
>
> 1. when the function explicitly returns, does it return an object?
> 2. does the function ever finish without returning or throwing or exiting?
>
> Only the first actually involves a strict type check. The second is a
> generic behaviour check, triggered by the existence of a return type. This
> is essentially the same check that we want to trigger with
> "noreturn"/"never".
>
> In fact, as someone recently pointed out, running the following code
> *today* produces similar errors to the ones we propose:
>
> function php7Redirect() : noreturn {
> if (rand(0, 1)) {
> return "bad"; //  Fatal error: Uncaught TypeError
> }
> header("Location: https://php.net";);
> exit; // OK
> }
>
> Our RFC makes this code explicitly legal, and adds covariance. Indeed our
> implementation is small because it correctly treats "noreturn"/"never" as a
> type, allowing us to use the existing return type handling.
>


Re: [PHP-DEV] Inline conditional that returns null if falsy

2021-02-24 Thread David Rodrigues
Em qua., 24 de fev. de 2021 às 12:29, Michael Morris 
escreveu:

> Javascript has this now though support isn't widespread.
>
>
> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
>
> The most similar way to do it in PHP would be ?->
>

Optional chaining is not the same.

My suggestion is similar to:

$variable = $user->exists ? $user->fullname; // suggestion (will return
null if expression is falsy)
$variable = $user->exists ? $user->fullname : null; // same as

Optional chaining is:

$variable = $user?->exists; // PHP 8
$variable = $user && $user->exists ? true : null; // same as


Re: [PHP-DEV] preg_replace(string, null) is allowed?

2021-02-17 Thread David Rodrigues
Thanks!

There is a reason why it is not supported anymore?

There is a difference in output or performance, maybe?


Atenciosamente,
David Rodrigues


Em qua., 17 de fev. de 2021 às 17:37, Nikita Popov 
escreveu:

> On Wed, Feb 17, 2021 at 9:28 PM David Rodrigues 
> wrote:
>
>> Hello!
>>
>> I am in doubt if passing null as the second argument to preg_replace() is
>> valid. Actually, it works as expected.
>>
>> https://3v4l.org/0TITS
>>
>> But doc only accepts array|string.
>>
>> I am asking for it because PhpStorm will not accept it. So if it is valid,
>> I will do a PR to PS stubs.
>>
>
> On PHP 8.1.0-dev your example prints:
>
> Deprecated: preg_replace(): Passing null to parameter #2
> ($replacement) of type array|string is deprecated in %s on line 3
>
> Under strict_types=1 it already throws.
>
> So no, it is not valid.
>
> Regards,
> Nikita
>
>


[PHP-DEV] preg_replace(string, null) is allowed?

2021-02-17 Thread David Rodrigues
Hello!

I am in doubt if passing null as the second argument to preg_replace() is
valid. Actually, it works as expected.

https://3v4l.org/0TITS

But doc only accepts array|string.

I am asking for it because PhpStorm will not accept it. So if it is valid,
I will do a PR to PS stubs.

Thanks!


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] Inline conditional that returns null if falsy

2021-02-13 Thread David Rodrigues
Em sáb., 13 de fev. de 2021 às 00:11, Marco Pivetta 
escreveu:

> Hey David,
>
> Even upfront, this looks like a quite bad idea: either you have an empty
> collection, or you have a collection with elements in it, but `null` is a
> very different concept that isn't homogeneous with the resulting type.
>
> I've updated multiple projects in the past where `array|null` was used as
> return type for a collection-alike endpoint, removing `null` and replacing
> it with an empty iterable instead.
>

This was just one of the examples I have, but I still think it is valid.
Creating an empty collection costs resources that could be avoided in
situations where null could be used (as is most of my real use cases).

But there are other situations where we can use different situations to use
this type of resource.

One of the examples I have is when I need to include a class in an HTML
element conditionally. There are probably better ways, but this is a quick
one for simple situations:

... vs.
...

It is much easier to read, and I believe that the cost for language would
be minimal, and perhaps even more optimized than the use of ?:.



Atenciosamente,
David Rodrigues


Em sáb., 13 de fev. de 2021 às 00:11, Marco Pivetta 
escreveu:

> Hey David,
>
> On Fri, Feb 12, 2021, 20:24 David Rodrigues 
> wrote:
>
>> Hello!
>>
>> It is just a suggestion to be discussed.
>>
>> A lot of places on my projects I have codes like:
>>
>> $companies = $user->companies->count()
>> ? new Collection($user->companies)
>> : null;
>>
>
> Even upfront, this looks like a quite bad idea: either you have an empty
> collection, or you have a collection with elements in it, but `null` is a
> very different concept that isn't homogeneous with the resulting type.
>
> I've updated multiple projects in the past where `array|null` was used as
> return type for a collection-alike endpoint, removing `null` and replacing
> it with an empty iterable instead.
>
>>


[PHP-DEV] Inline conditional that returns null if falsy

2021-02-12 Thread David Rodrigues
Hello!

It is just a suggestion to be discussed.

A lot of places on my projects I have codes like:

$companies = $user->companies->count()
? new Collection($user->companies)
: null;

So $companies will be null except if the user has companies.

My suggestion is create some kind of inline conditional to works like that:

$companies = $user->companies->count() => new Collection($user->companies);

If the conditional ($user->companies->count()) is true, then will return
the value (after =>), else will be null.

In my current work project, I have more than 100+ occurrences like that.

So some more examples:

$userCategory ? $userCategory->getTitle() : null
-> It could be optimized to the new nullsafe operator
$userCategory?->getTitle()

return $languageFirst instanceof LanguageExperience
? $languageFirst->title : null;
-> This not, with my suggestion we have:
return $languageFirst instanceof LanguageExperience =>
$languageFirst->title;

The => is just a suggestion, other options using existing keywords is:
return expr() then output();
return expr(): output();

I do not know if other languages support something like that.

Thanks!


Atenciosamente,
David Rodrigues


[PHP-DEV] PHP.net is down?

2021-01-07 Thread David Rodrigues
Hello!

I cannot access php.net anymore. error 500.


Atenciosamente,
David Rodrigues


[PHP-DEV] Traits "implements" support

2020-11-26 Thread David Rodrigues
Hello!

Now with PHP 8, traits supports abstract functions that should be
implemented by the class that uses this trait.

So is it now possible that traits could have support to implements too? So
when class uses this trait, it will be an implementation of X interface and
will have to implement methods based on it.

interface A {
public function x();
}

trait B implements A {
public function y() { $this->x(); }
// public function x() still not implemented.
}

class Z { // impliticy implements A interface due to B trait.
use B;
public function x() {} // required!
}


Atenciosamente,
David Rodrigues


[PHP-DEV] Strict switch

2020-11-26 Thread David Rodrigues
Hello!

With PHP 8 we have match(), that is a switch strict expression-like. But
strict is not strict, and it could cause confusion because switch() and
match() are pretty similar.

I believe that this has already been discussed, but it would be interesting
to re-evaluate the possibility of a strict() with support for strict.

In order not to generate BC, my suggestion is to attach a specific keyword
for this purpose, or a similar alternative.

(0) switch(8.0) { case '8.0'; return 'no'; case 8.0: return 'yes'; } // no?

(1) strict switch(8.0) { case '8.0'; return 'no'; case 8.0: return 'yes'; }
// yes
(2) switch strict(8.0) { ... } // yes
(3a) switch(8.0, true) { ... } // yes
(3b) switch(8.0, strict: true) { ... } // yes (named argument)

Or then in the "case":

(4) switch(8.0) { strict case 8.0: ... } // yes
(5) switch(8.0) { case strict 8.0: ... } // yes

Or allowing operators (this would be the most flexible way, as it would
allow for a number of other features):

(6) switch(8.0) { case === 8.0: ... } // yes



Atenciosamente,
David Rodrigues


[PHP-DEV] Method parameter promotion support

2020-11-26 Thread David Rodrigues
Hello!

It is just an idea to discuss. PHP 8 now supports parameter promotion via
constructor. Could this idea also work for common methods?

public function setAge(private int $age) {}
===
private int $age;
public function setAge(int $age) { $this->age = $age; }

The only problem I can see would be the difficulty of identification of the
possible properties, since it would be necessary to check all method
signatures to know about all possible properties.

In this case, perhaps, it would be enough to allow the promotion only if
the property already exists.

private int $age; // Required.
public function setAge(private int $age) {}

Just to think about whether it is possible to think of something along
these lines, but I'm still not sure if it's a good option.


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] [RFC] Draft - Closure self reference

2020-11-20 Thread David Rodrigues
> No we can't, try it (Parse error). The correct order is
> "function() use($x): Type".

Oh! You are right!

In this case, we still have the old idea:
function() as $lambda use ($x): int {}

> Ugh. That's ugly.  I want to say we should fix it, but the horse has left
the stables, so it's too late to enforce the right (to me) ordering.

Yeah, but is there any way to go back now? :/


Atenciosamente,
David Rodrigues


Em sex., 20 de nov. de 2020 às 16:08, Sara Golemon 
escreveu:

> On Fri, Nov 20, 2020 at 12:58 PM Guilliam Xavier <
> guilliam.xav...@gmail.com> wrote:
>
>> > I don't know if that would be a problem, because today we can have it
>> > "function(): Type use($x)", so "Type use($x)"?
>> >
>>
>> No we can't, try it (Parse error). The correct order is
>> "function() use($x): Type".
>>
>>
> Ugh. That's ugly.  I want to say we should fix it, but the horse has left
> the stables, so it's too late to enforce the right (to me) ordering.
>
> -Sara
>


Re: [PHP-DEV] [RFC] Draft - Closure self reference

2020-11-20 Thread David Rodrigues
> Is it `returnType as $thing` ?  That doesn't read well, but I don't see
us making return type movable.  as/use should be placable in either order,
but maybe we give them required order anyway?

I don't know if that would be a problem, because today we can have it
"function(): Type use($x)", so "Type use($x)"? I have to agree that it may
sound strange at first, but I also can't imagine many ways of doing things
differently without creating more complexities.

(1) function as $lambda (... $args): returnType use ($captures...) {}
(2) function (... $args) as $lambda: returnType use ($captures...) {}
(3) function (... $args): returnType as $lambda use ($captures...) {} //
original suggestion
(4) function (... $args): returnType use ($captures...) as $lambda {}
(4.b) function (... $args): returnType as $lambda {} // without use() will
be same as (3)

Or, define a "inline function" with its own name, visible only within the
scope itself. Similar to how JS works.

(5) function $lambda(... $args): returnType use ($captures...) {}

To be honest, as I typed what came to mind, I ended up preferring this last
option.

JS way:

function fb(n) {
  if (n === 0) return 0;
  if (n === 1) return 1;

  return fb(n - 1) + fb(n - 2);
}

PHP (self-referenced) way:

function $fb($n): int {
  if ($n === 0) return 0;
  if ($n === 1) return 1;

  return $fb($n - 1) + $fb($n - 2);
}

Currently PHP will accepts the same JS solution, but it will exposes fb()
to global scope and could causes errors:

function test() {
  function fb($n): int
  {
if ($n === 0) return 0;
if ($n === 1) return 1;

return fb($n - 1) + fb($n - 2);
  }

  var_dump(fb(10));
}

test();
test(); // Fatal error: Cannot redeclare fb()


Atenciosamente,
David Rodrigues


Em sex., 20 de nov. de 2020 às 12:14, Sara Golemon 
escreveu:

> On Wed, Nov 11, 2020 at 12:37 PM David Rodrigues 
> wrote:
>
>> My suggestion is to reuse the keyword `as` to set a variable that will
>> represent its own closure. It is more flexible once that we could choose
>> any name and reuse in nested closures. It is pretty similar to how SQL
>> works too.
>>
>> function fn1() as $lambda1 {
>> return function() as $lambda2 use ($lambda1) {
>> return [ gettype($lambda1), gettype($lambda2) ];
>> };
>> }
>>
>>
> My initial reaction to this is:  Technically doable (easy even), but looks
> a bit... ugly? weird? surprising?
>
> I think my main objection to it is how much is now stacked after the
> parameter list:
>
> function($args...) : returnType as $local use ($captures...) {
>   ...
> };
>
> That's a lot of... stuff (granted, we have most of it already) and how it
> looks when stacked together gets funky.
>
> Is it `returnType as $thing` ?  That doesn't read well, but I don't see us
> making return type movable.  as/use should be placable in either order, but
> maybe we give them required order anyway?
>
> TLDR; Long winded way to say I'm not inherently against this, and I like
> the idea of a lambda being able to recurse (not that I can ever recall
> having use for it, but maybe I fell back on named functions for that), I
> just think it's getting a bit wordy.
>
> -Sara
>


[PHP-DEV] strict_types will be default at some moment?

2020-11-11 Thread David Rodrigues
Hello!

I have been asked by a friend if declare(strict_types=1) will be applied by
default for some version of PHP, like 9.x or will it be always required by
all scripts forever. Someone can tell me?

If yes, what is the reason for requiring it? Why it can't be the default
behavior (or maybe, the unique behavior).


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] [RFC] Draft - Closure self reference

2020-11-11 Thread David Rodrigues
I think that introducing a new variable, that even uncommon, could cause BC.

My suggestion is to reuse the keyword `as` to set a variable that will
represent its own closure. It is more flexible once that we could choose
any name and reuse in nested closures. It is pretty similar to how SQL
works too.

function fn1() as $lambda1 {
return function() as $lambda2 use ($lambda1) {
return [ gettype($lambda1), gettype($lambda2) ];
};
}


Atenciosamente,
David Rodrigues


Em qua., 11 de nov. de 2020 às 14:59, Christoph M. Becker 
escreveu:

> On 11.11.2020 at 18:39, Dan Ackroyd wrote:
>
> > On Tue, 10 Nov 2020 at 17:39, Hans Henrik Bergan 
> wrote:
> >>
> >> something i'm missing from Javascript is the ability to give names to
> >> closures, ...the name is optional, and only visible inside the closure
> >> itself, and unfortunately this is not legal in PHP, i wish it was.
> >
> > I really like that...but unfortunately that wouldn't work in PHP.
> >
> > In JS, when a function is declared inside another function, the name
> > of it is limited to the scope of the containing function. In PHP, when
> > a function is declared inside another function, it is put into the
> > current namespace's global scope.
> >
> > Changing how scope works in PHP would be too large a change for just
> this.
>
> In JavaScript, a named function expression is different to a function
> declaration:
>
> var fn = function foo() {console.log('blah')}
> foo()
> => Uncaught ReferenceError: foo is not defined
>
> vs.
>
> function foo() {console.log('blah')}
> foo()
> => blah
>
> So the named function expression is still an anonymous function; the
> label is only defined inside of the function body.
>
> Christoph
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


[PHP-DEV] Supports to ?:= assignment operator

2020-11-11 Thread David Rodrigues
Hello!

PHP currently supports ??= assignment, as shortly to $a = $a ?? null, but
it does not supports ?:= as shortly to $a = $a ?: null.

There are some reason to that?

- https://wiki.php.net/rfc/null_coalesce_equal_operator
- https://wiki.php.net/rfc/short_ternary_equal_operator

Thanks!


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] [RFC] Short-function syntax

2020-10-26 Thread David Rodrigues
> The use of > instead of => could if possible indicate the method being
void
> and reduce even more:

I think that for void, it could just identify it and not return nothing
automatically.

function a(): int => b(); // equivalents to function a(): int { return b();
}
function x(): void => y(); // equivalents to function x(): void { y(); }

Atenciosamente,
David Rodrigues


Em seg., 26 de out. de 2020 às 11:23, Michał Marcin Brzuchalski <
michal.brzuchal...@gmail.com> escreveu:

> Hi Larry,
>
> I'm wondering why we hadn't thought yet about reducing the need for $this
> in this syntax.
> Since arrow functions have an ability to capture variables defined in
> parent scope why not
> think of the same for class properties which will automatically reduce
> short methods verbosity.
>
> class X {
> public function __construct(private int $foo, private int $bar) {}
> public function getFoo(): int => $foo;
> public function getBar(): int => $bar;
> }
>
> And then going further why not removing = from arrow which indicated that
> there is no return value for void functions:
>
> class X {
> public function __construct(private int $foo, private int $bar) {}
> public function getFoo(): int => $foo;
> public function setFoo(int $value): void > $foo = $value;
> public function getBar(): int => $bar;
> public function setBar(int $value): void > $bar = $value;
> }
>
> The use of > instead of => could if possible indicate the method being void
> and reduce even more:
>
> class X {
> public function __construct(private int $foo, private int $bar) {}
> public function getFoo(): int => $foo;
> public function setFoo(int $value) > $foo = $value;
> public function getBar(): int => $bar;
> public function setBar(int $value) > $bar = $value;
> }
>
> Would it be possible?
>
> If not I think we should reanimate property accessors.
>
> Just dropping my 50 cents.
>
> Best regards,
> Michał Marcin Brzuchalski
>
> wt., 20 paź 2020 o 20:20 Larry Garfield 
> napisał(a):
>
> > A while back, Nikita mentioned that it should now be easy to offer an
> > abbreviated syntax for functions that are just a single expression.  I
> > decided to take a crack at it and it turns out he was right.  I thus
> offer
> > this RFC:
> >
> > https://wiki.php.net/rfc/short-functions
> >
> > Hopefully I made a decent enough case for it.  It's entirely a
> convenience
> > factor, but I think for many OOP cases (getter methods and factored out
> > operations) and functional cases (where functions should generally be a
> > single expression conceptually) it does make the code nicer, more
> compact,
> > and more readable.
> >
> > *dons flame retardant suit*
> >
> > --
> >   Larry Garfield
> >   la...@garfieldtech.com
> >
> > --
> > PHP Internals - PHP Runtime Development Mailing List
> > To unsubscribe, visit: https://www.php.net/unsub.php
> >
> >
>


[PHP-DEV] static vars must allow expressions

2020-10-05 Thread David Rodrigues
Hello!

I would like to suggest that static vars must allow expressions too.
Currently it only supports scalar values, but different to consts, it could
be manipulated by its own function that uses that.

https://www.php.net/manual/en/language.variables.scope.php#language.variables.scope.static

Currently you could uses like:

function test() {
static $x;
$x++;
var_dump($x);
}

test(); // 1
test(); // 2

So my idea is allow an initial value to be defined by a more complex
expression, like:

function test() {
static $configurationHandler = Configuration::getInstance();
$configurationHandler->doSomething();
}

Additionally, I thought that it might be necessary to implement some new
methods for ReflectionFunction / ReflectionMethod, in which it allows to
reset or check the current value.

(new ReflectionFunction('test'))->hasStaticVariable('x'); // true
(new ReflectionFunction('test'))->issetStaticVariable('x'); // true
(new ReflectionFunction('test'))->setStaticVariable('x', 123); // void
(new ReflectionFunction('test'))->getStaticVariable('x'); // 2
(new ReflectionFunction('test'))->unsetStaticVariable('x'); // void

or

(new ReflectionFunction('test'))->getStaticVariable('x'); //
ReflectionProperty (or ReflectionVariable)

One of the questions that can happen is about the context conflict, but it
already occurs:

class Test {
public function test(): void {
static $x = 0;

$x++;

var_dump($x);
}
}

(new Test)->test(); // 1
(new Test)->test(); // 2

Note that $x will share the context like a static property, even if it been
called from a non-static context.



Atenciosamente,
David Rodrigues


Re: [PHP-DEV] RFC: execution opcode file without php source code file

2020-10-02 Thread David Rodrigues
Hello folks,

Instead of an opcode without a php source file, that I imagine is to
protect the code itself, why not a method to encrypt phar files (not like a
password). I do not know if exists a secure method to decrypt to execute
only, without reveals the original source code, but maybe it could be done.
So opcode could be generated based on encrypted phar to give more speed.


Atenciosamente,
David Rodrigues


Em sex., 2 de out. de 2020 às 13:52, Rowan Tommins 
escreveu:

> On Thu, 1 Oct 2020 at 16:13, Dik Takken  wrote:
>
> > The only use case I see is to package commercial closed source
> > applications as Docker containers. That allows the packager to ship the
> > compiled code along with the exact PHP version and configuration that
> > can run it reliably.
> >
>
>
> Could this not be achieved by freezing the existing OpCache file cache into
> the Docker image and telling OpCache not to validate timestamps, so that it
> always loads from the cache? That way, your application wouldn't even need
> to be modified, as the require_once lines would still refer to the original
> source paths.
>
> Regards,
> --
> Rowan Tommins
> [IMSoP]
>


Re: [PHP-DEV] __isset() and null value

2020-09-04 Thread David Rodrigues
Maybe you just can implements your own method to check? Like your exists()
example.

Em sex, 4 de set de 2020 15:08, Michael Voříšek - ČVUT FEL <
voris...@fel.cvut.cz> escreveu:

> Your examples provide code for checking the existance of real
> properties. But how to check existance of a magic one?
>
> The best is currently __isset(), but to comply with isset() definition,
> it should not return true when the magic property has null value, thus I
> belive, there is currently not way (provided by php language) to check
> for existance of magic property.
>
> With kind regards / Mit freundlichen Grüßen / S přátelským pozdravem,
>
> Michael Voříšek
>
> On 4 Sep 2020 19:23, Marco Pivetta wrote:
>
> > Heya,
> >
> > On Fri, Sep 4, 2020 at 7:03 PM Michael Voříšek - ČVUT FEL <
> voris...@fel.cvut.cz> wrote:
> >
> >> isset() returns false for null
> >>
> >> __isset() should return the same, but then if magic property with null
> >> value exists, there is no way to detect it
> >>
> >> Example: https://3v4l.org/GqUsh
> >>
> >> this is currently an limitation of php
> >>
> >> Ideally, we should introduce __exist() which should return true even if
> >> value is null and for BC autoimplement __isset() based on it and __get,
> >> ie.
> >>
> >> function __isset($n) { return $this->__exist($n) && $this->__isset($n)
> >> !== null; }
> >
> > I'd endorse **NOT** checking for property existence on objects that
> don't have a clearly defined interface/type: that's something for a static
> analyzer, not (usually) for runtime code.
> >
> > If you still need to do that (anti-patterns such as stuffing things in
> `stdClass` instances), checking if a property is defined is trivial with
> reflection:
> >
> > ```php
> >  >
> > class SomethingMagicAndTerriblyUgly
> > {
> > public $foo = null;
> > private $bar = null;
> > }
> >
> > var_dump((new
> ReflectionClass(SomethingMagicAndTerriblyUgly::class))->hasProperty('foo'));
> > var_dump((new
> ReflectionClass(SomethingMagicAndTerriblyUgly::class))->hasProperty('bar'));
> > var_dump((new
> ReflectionClass(SomethingMagicAndTerriblyUgly::class))->hasProperty('baz'));
>
> > ```
> >
> > https://3v4l.org/pVC4j
> >
> > Checking if a **public** property exists at runtime is done via
> `array_key_exists()`, not via `isset()`:
> >
> > ```php
> >  >
> > class SomethingMagicAndTerriblyUgly
> > {
> > public $foo = null;
> > private $bar = null;
> > }
> >
> > var_dump(array_key_exists('foo', (array) (new
> SomethingMagicAndTerriblyUgly)));
> > var_dump(array_key_exists('bar', (array) (new
> SomethingMagicAndTerriblyUgly)));
> > ```
> >
> > https://3v4l.org/ZLSjq
> >
> > Marco Pivetta
> >
> > http://twitter.com/Ocramius
> >
> > http://ocramius.github.com/


Re: [PHP-DEV] Pass source object to clone like __clone($origThis)

2020-09-03 Thread David Rodrigues
Just to I know, it can't be done by an intermediary method like my previous
example? Why are the limitations to that?

About PR, could you provide some additional tests?

Thanks!

Em qui, 3 de set de 2020 13:37, Michael Voříšek - ČVUT FEL <
voris...@fel.cvut.cz> escreveu:

> The goal is to be able to access the original object and it's id/hash.
>
> Usecases:
>
> - something is associated with the object using the object id/hash and
> it needs to be cloned as well
>
> we need the original object to obtain it's id/hash for spl_object_id and
> spl_object_hash methods
>
> - bounded Closures ar associated with the original object and they needs
> to be rebound to the cloned object
>
> example:
>
> public function __clone(self $origThis)
> {
> if ((new \ReflectionFunction($this->fx))->getClosureThis() ===
> $origThis) {
> $this->fx = \Closure::bind($this->fx, $this);
> }
> }
>
> Modification of php is simple:
>
>
> https://github.com/php/php-src/pull/6063/files#diff-beea8c5a8ceb318220b34b73e4ecfc98R252
>
>
> we simply pass the old object as 1 parameter. I belive, passing old
> object have positives and no performance nor compatibility impact. All
> other current solutions require an extra property and a lot of code, as
> assigning in constructor is not enough (due serialization etc.), or it
> is even impossible, if object was created using reflection without
> constructor.
>
> With kind regards / Mit freundlichen Grüßen / S přátelským pozdravem,
>
> Michael Voříšek
>
> On 3 Sep 2020 18:00, Sara Golemon wrote:
>
> > On Thu, Sep 3, 2020 at 10:40 AM David Rodrigues 
> > wrote:
> >
> >> Now I rethinked about what I said. Really, maybe clone is not the best
> >> option. So maybe we can just use a method that will clone and will have
> >> access to both informations. But I don't know if it solves the original
> >> message.
> >>
> >> public function getUserCopy() {
> >> $userCopy = clone $this;
> >> $this->copies[] = $userCopy;
> >>
> >> return $userCopy;
> >> }
> > If your goal is to track copies, then a static makes much more sense.
> >
> > class AllKnowing {
> > private static $copies = [];
> >
> > public function __construct(...) {
> > self::$copies[] = $this;
> > 
> > }
> >
> > public function __clone() {
> > self::$copies[] = $this;
> > }
> > }
> >
> > -Sara


Re: [PHP-DEV] Pass source object to clone like __clone($origThis)

2020-09-03 Thread David Rodrigues
It was just an example to avoid modify how clone works, using existing
features. :)

Em qui, 3 de set de 2020 13:00, Sara Golemon  escreveu:

> On Thu, Sep 3, 2020 at 10:40 AM David Rodrigues 
> wrote:
>
>> Now I rethinked about what I said. Really, maybe clone is not the best
>> option. So maybe we can just use a method that will clone and will have
>> access to both informations. But I don't know if it solves the original
>> message.
>>
>> public function getUserCopy() {
>> $userCopy = clone $this;
>> $this->copies[] = $userCopy;
>>
>> return $userCopy;
>> }
>>
>>
> If your goal is to track copies, then a static makes much more sense.
>
> class AllKnowing {
> private static $copies = [];
>
> public function __construct(...) {
> self::$copies[] = $this;
> 
> }
>
> public function __clone() {
> self::$copies[] = $this;
>}
> }
>
> -Sara
>


Re: [PHP-DEV] Pass source object to clone like __clone($origThis)

2020-09-03 Thread David Rodrigues
Now I rethinked about what I said. Really, maybe clone is not the best
option. So maybe we can just use a method that will clone and will have
access to both informations. But I don't know if it solves the original
message.

public function getUserCopy() {
$userCopy = clone $this;
$this->copies[] = $userCopy;

return $userCopy;
}

Considering it, we have access to both now, with "write to source" support
with no additional feature need.

Em qui, 3 de set de 2020 11:21, Sara Golemon  escreveu:

> On Wed, Sep 2, 2020 at 2:11 PM David Rodrigues 
> wrote:
>
>> I understand... seems that `$this` is very confusing inside `__clone()`:
>> when writing, it writes to the clone, when reading it reads from original.
>>
>>
> That's not an accurate description of what happens today.
>
> $newObj = clone $oldObj;
> // 1. Engine creates a new instance of get_class($oldObj), without calling
> the constructor
> // 2. Engine copies all properties from the old object to the new object
> // 3. Engine invokes $newObj->__clone()
>   public function __clone() {
> // Userspace object handles any property specific re-initialization
> required.
> // $this always refers to the new object here.
>  }
>
> The question Niki asked is appropriate; What would one want to do to
> $oldObj here?
> If the goal is to read from the old object, then you have that already.
> The new object is a perfect copy, so read from that.
> If the goal is to write to the old object, then justify why you need to do
> so, because it's not a clone operation at that point.
>
> -Sara
>


Re: [PHP-DEV] Draft RFC: foreach iteration of keys without values

2020-09-03 Thread David Rodrigues
Do you think that it could be proxied? I mean, optimize foreach
(array_keys()...) syntax to not call array_keys() in fact, but a optimized
version of foreach to handle key only. I don't know it opcache could do
that, and if it already does.

Em qui, 3 de set de 2020 12:12, Levi Morrison via internals <
internals@lists.php.net> escreveu:

> On Thu, Sep 3, 2020 at 8:32 AM Sara Golemon  wrote:
> >
> > On Thu, Sep 3, 2020 at 4:19 AM Markus Fischer 
> wrote:
> >
> > > > I currently use foreach (array_keys($array) as $key) { ... }
> > > >   to avoid complains from code analysers on unused var, is it slower?
> > >
> > > one argument brought forward initially (sorry, can't find the email
> > > right now) is the resource management: array_keys() has to create a
> copy
> > > [*] which might be an issue depending on the size of data.
> > >
> > >
> > While I like the idea of more explicit syntax to show intent over a mere
> > convention of $_ being an ignorable var, I do need to call out the
> foreach
> > (array_keys(...) argument as being a poor motivator.
> >
> > IF (and I heavily stress "if" here) this pattern is common among people
> > trying to show explicit intent and IF it represents a noticeable
> slowdown,
> > then the solution for it is for the engine to optimize around that by
> > transforming it during compile time.  That lets us fix all usages
> > instantaneously without user interaction, and more importantly it allows
> > users to focus on their code being readable (and thereby maintainable)
> > according to whatever coding standards they choose to apply.
> >
> > Again, that same argument is why I actually like the proposal overall.
> Not
> > because it's so much more performant, but because it empowers developers
> to
> > write code in a way that will be most readable and maintainable to them,
> > should they happen to just not like the $_ unused var pattern (which is a
> > legit thing to dislike).
> >
> > -Sara
>
> Question for those who know about opcache optimizations: is it
> feasible to avoid fetching the current value if the value is otherwise
> unused and the variable-variable features are not used either?
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Global functions any() and all() on iterables

2020-09-03 Thread David Rodrigues
Do you think that it could be proxied too? I mean, optimize foreach
(array_keys()...) syntax to not call array_keys() in fact, but a optimized
version of foreach to handle key only.

Em qui, 3 de set de 2020 11:36, Sara Golemon  escreveu:

> On Mon, Aug 31, 2020 at 6:56 PM tyson andre 
> wrote:
>
> > I've created an RFC for https://wiki.php.net/rfc/any_all_on_iterable
> >
> >
> I've probably reached this thread too late, but I'm going to throw out my
> old chestnut that these things don't belong in the engine. They belong in
> userspace.
>
> 1. Instant forward compatibility (any version can run `composer install`)
> 2. Instant bug fixes and improvements (no waiting for the next minor
> version of PHP)
> 3. Better visibility from the JIT (not having to cross userspace/internals
> border is good)
>
> And that's all I'm going to say because I'm pretty sure I've lost the
> argument long ago, but here's my any/all/none (and other) methods from
> years ago (IN USERSPACE!):
> https://github.com/phplang/generator/blob/master/src/iterable.php
>
> -Sara
>


Re: [PHP-DEV] Pass source object to clone like __clone($origThis)

2020-09-03 Thread David Rodrigues
I don't see problem to allow modify the original object, once that you are
doing it by using a new argument, and not the $this itself.

Em qui, 3 de set de 2020 08:49, Pedro Magalhães  escreveu:

> On Wed, Sep 2, 2020 at 7:41 PM Michael Voříšek - ČVUT FEL <
> voris...@fel.cvut.cz> wrote:
>
> > do you have anything against updating PHP to pass "instance before
> > cloned" to any __clone call from php?
> >
>
> Yes, I think that allowing the original object to be modified by a cloning
> operation could be the cause for a lot of confusion. If we had a proper way
> to make it read-only I wouldn't mind, but as is, it doesn't sound like a
> good idea.
>


Re: [PHP-DEV] Pass source object to clone like __clone($origThis)

2020-09-02 Thread David Rodrigues
I understand... seems that `$this` is very confusing inside `__clone()`:
when writing, it writes to the clone, when reading it reads from original.

Seems valid a new optional parameter definition with the original source.



Atenciosamente,
David Rodrigues


Em qua., 2 de set. de 2020 às 15:41, Michael Voříšek - ČVUT FEL <
voris...@fel.cvut.cz> escreveu:

> Hi, please look at
>
> https://stackoverflow.com/questions/63675888/get-original-source-instance-in-clone
>
>
> do you have anything against updating PHP to pass "instance before
> cloned" to any __clone call from php?
>
> no BC - user may accept this extra argument or declare function
> __clone() without any param like now
>
> With kind regards / Mit freundlichen Grüßen / S přátelským pozdravem,
>
> Michael Voříšek


Re: [PHP-DEV] Draft RFC: foreach iteration of keys without values

2020-09-02 Thread David Rodrigues
I think "void" is a good solution and is very clear, compared to "_".

[void, void, $username] = getUserData();


Atenciosamente,
David Rodrigues


Em qua., 2 de set. de 2020 às 10:57, Dik Takken 
escreveu:

> On 02-09-2020 15:35, Chase Peeler wrote:
> > Isn't the underscore an alias for gettext()?
>
> You are right, it is. Now this does not necessarily mean that underscore
> cannot be used for ignored variables. Depending on the context in which
> it is used an underscore may or may not be ambiguous.
>
> Since we are talking about using underscore in places where a variable
> name is expected, there may not be any problem at all. But we should be
> aware of all cases in which ambiguous syntax could emerge and identify
> any issues. So thanks a lot for pointing out this possible trouble maker!
>
> Regards,
> Dik Takken
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] array_reject() as counterpart of array_filter()

2020-08-31 Thread David Rodrigues
> I wouldn't vote against a flag on array_filter(), because doing the quick
and easy thing is very much in PHP's DNA, but I think we can cover a lot
more ground with a more general purpose solution that leaves userspace to
deal with bigger problems.

I totally agree with you.

Atenciosamente,
David Rodrigues


Em seg., 31 de ago. de 2020 às 13:00, Sara Golemon 
escreveu:

> On Mon, Aug 31, 2020 at 10:35 AM David Rodrigues 
> wrote:
> >> It should be possible for the engine (at some layer) to look at that
> closure
> >> and see that it's just negating some proxied call and elide setting up
> the
> >> intermediate frame.  Microoptimizations SHOULD be the engine's job, not
> userspace's.
> >>
> >
> > I really think that it should be a good solution, but how hard should it
> be to create a proxy like that?
> >
>
> We already have a few examples of proxies of this sort.
> Closure::fromCallable() comes to mind in particular.  We could detect the
> `fn($x) => !y($x)` pattern and replace it with a callable of y with
> negation (and a few other common idioms).
>
> I wouldn't vote against a flag on array_filter(), because doing the quick
> and easy thing is very much in PHP's DNA, but I think we can cover a lot
> more ground with a more general purpose solution that leaves userspace to
> deal with bigger problems.
>
> -Sara
>


Re: [PHP-DEV] array_reject() as counterpart of array_filter()

2020-08-31 Thread David Rodrigues
> Just to be clear, I think you're referring to "compared to the case of a
bare string callable", e.g.: array_filter($arr, 'is_numeric')   vs.
array_filter($arr, fn($x) => !is_numeric($x));

Yes, because I can optimize it when array_filter() is "positive-only", but
I can't when I need to be "negative-only", so I depend on a fn($x) =>
!is_numeric($x). I not have a php-src enabled for now, but I pretends to
have soon so I can try to apply it directly to C and compile it, so for now
I am limited to what PHP could do.

> "Citation required" still stands in that case, but even if that function
call overhead does amount to 70% (and for inlined functions like is_numeric
it might), I would say that's not cause to add complexity to the filter
function, but rather cause to look at ways to optimize the code that exists
in the wild.  It should be possible for the engine (at some layer) to look
at that closure and see that it's just negating some proxied call and elide
setting up the intermediate frame.  Microoptimizations SHOULD be the
engine's job, not userspace's.

I really think that it should be a good solution, but how hard should it
be to create a proxy like that?



Atenciosamente,
David Rodrigues


Em seg., 31 de ago. de 2020 às 11:55, Sara Golemon 
escreveu:

> On Mon, Aug 31, 2020 at 9:41 AM David Rodrigues 
> wrote:
>
>> > I agree with Larry that userland implementation is trivial enough that
>> it
>> > doesn't really need to be implemented in core. It's just syntactic sugar
>> > that's probably more trouble than it's worth.  That being said, I'm by
>> far
>> > an expert when it comes to core, so I can't really say 1.) what
>> performance
>> > benefits it would provide or 2.) how hard (or easy) it would be to
>> > implement.
>>
>> 1. array_reject() should be 70% faster than array_filter(arr, fn() ...)
>> version;
>>
>>
> Citation Needed.
>
> Just to be clear, I think you're referring to "compared to the case of a
> bare string callable", e.g.: array_filter($arr, 'is_numeric')   vs.
> array_filter($arr, fn($x) => !is_numeric($x));
>
> "Citation required" still stands in that case, but even if that function
> call overhead does amount to 70% (and for inlined functions like is_numeric
> it might), I would say that's not cause to add complexity to the filter
> function, but rather cause to look at ways to optimize the code that exists
> in the wild.  It should be possible for the engine (at some layer) to look
> at that closure and see that it's just negating some proxied call and elide
> setting up the intermediate frame.  Microoptimizations SHOULD be the
> engine's job, not userspace's.
>
> -Sara
>


Re: [PHP-DEV] array_reject() as counterpart of array_filter()

2020-08-31 Thread David Rodrigues
> The original poster had a typo, I think, and meant array_reject not
> array_reverse. He basically implemented the solution that Larry was
> referring to, before Larry referred to it.

Yes! It means to be "array_reject()" instead of "array_reverse()". And my
syntax is wrong too, actually it should be array_reject(array, callback)
like array_filter(array, callback).

> I agree with Larry that userland implementation is trivial enough that it
> doesn't really need to be implemented in core. It's just syntactic sugar
> that's probably more trouble than it's worth.  That being said, I'm by far
> an expert when it comes to core, so I can't really say 1.) what
performance
> benefits it would provide or 2.) how hard (or easy) it would be to
> implement.

1. array_reject() should be 70% faster than array_filter(arr, fn() ...)
version;

2. basically is just replicate array_filter() code with a "not" operator at
some point.


But, analysing array_filter() now, I think that we can consider just a new
flag, instead a new function: array_filter($array, $callback,
ARRAY_FILTER_REJECT), so the implementation will be very simple and will
not need to create a new function to userland.


PS.: the array_reject() name suggestion is based on the lodash version (
https://lodash.com/docs/4.17.15#reject).



Atenciosamente,
David Rodrigues


Em seg., 31 de ago. de 2020 às 11:08, Chase Peeler 
escreveu:

> On Mon, Aug 31, 2020 at 9:52 AM Josh Bruce  wrote:
>
> > Just to confirm
> >
> > array_filter(“!is_int”, $collection)
> >
> > Would result in a collection of only non-integers??
> >
> >
> No, you'd have to put it in a closure
>
> The original poster had a typo, I think, and meant array_reject not
> array_reverse. He basically implemented the solution that Larry was
> referring to, before Larry referred to it.
>
> function array_reject(Callable $c, Array $a){
>   return array_filter(fn($item) => !$c($i), $a);
> }
>
> $non_ints = array_reject('is_int',[1,2,'a',3.5]);
>
> If you don't want to write your own array_reject method, and just handle it
> case-by-case, then it's still trivial
>
> $non_ints = array_filter(fn($i) => !is_int($i), [1,2,'a',3.5]);
>
> I do think there’s something to be said for the communication of intent
> > without syntax.
> >
> > array_without or array_reject reads easier to me than making sure to
> watch
> > for the bang.
> >
> >
> I agree with Larry that userland implementation is trivial enough that it
> doesn't really need to be implemented in core. It's just syntactic sugar
> that's probably more trouble than it's worth.  That being said, I'm by far
> an expert when it comes to core, so I can't really say 1.) what performance
> benefits it would provide or 2.) how hard (or easy) it would be to
> implement.
>
>
>
> > Cheers,
> > Josh
> >
> > >> On Aug 30, 2020, at 6:55 PM, Larry Garfield 
> > wrote:
> > >>
> > >> On Sun, Aug 30, 2020, at 9:38 AM, David Rodrigues wrote:
> > >> Currently we have array_filter(), but sometimes we need an inverse
> > function
> > >> like array_reject().
> > >> array_reject('is_null', [ 1, 2, null, 3 ]); // [ 1, 2, 3 ]
> > >> It could be easily implemented with:
> > >> function array_reverse($fn, $arr) { return array_filter(fn($item) =>
> > >> !$fn($item), $arr); }
> > >> Anyway, I think that It should be implemented by core, once that we
> have
> > >> array_filter().
> > >
> > > Any boolean function can be inverted with a simple ! in a short
> > closure.  I don't really see a need to do that in C.
> > >
> > > --Larry Garfield
> > >
> > > --
> > > PHP Internals - PHP Runtime Development Mailing List
> > > To unsubscribe, visit: https://www.php.net/unsub.php
> >
> > --
> > PHP Internals - PHP Runtime Development Mailing List
> > To unsubscribe, visit: https://www.php.net/unsub.php
> >
> >
>
> --
> Chase Peeler
> chasepee...@gmail.com
>


[PHP-DEV] array_reject() as counterpart of array_filter()

2020-08-30 Thread David Rodrigues
Currently we have array_filter(), but sometimes we need an inverse function
like array_reject().

array_reject('is_null', [ 1, 2, null, 3 ]); // [ 1, 2, 3 ]

It could be easily implemented with:

function array_reverse($fn, $arr) { return array_filter(fn($item) =>
!$fn($item), $arr); }

Anyway, I think that It should be implemented by core, once that we have
array_filter().


Re: [PHP-DEV] Re: Should hash comments be deprecated?

2020-08-29 Thread David Rodrigues
I have suggested on past a declare() to help in cases like that:

declare(php_version = "8.0");

It could be declared to new PHP files, so old files could supports # as
comments and new files will not.

Other option is supports 
escreveu:

> Hi internals,
>
> If it turns out that the impact on legacy applications, legacy libraries,
> or holding back upgrades is a concern for others
> (I'm not sure what the most common opinion is),
> another option would be a system ini setting
>
> `hash_comment = 0|1|2`
> 0 - disable `#comment` support completely when parsing/lexing - throw a
> ParseError while lexing and return T_ERROR in token_get_all
> 1 - (default) emit a compilation warning or deprecation notice when
> parsing files mentioning that hash comments will be removed in a future
> major release. Do this only for the first comment.
> 2 - allow it silently (possibly an unnecessary option to provide)
>
> Then, this could be gradually strictened
>
> - Forbid option 2 in php 8.x
> - change the default ini setting value to 0 in 8.x or 9.0
> - Add a configuration setting in php 8.x or 9.x to always disable hash
> comments
> - Remove support
>
> > Correct me if I'm wrong, but the shebang goes before the PHP opening
> > tag  > special case.
>
> Yes, shebang can only be parsed on the first line of a script - before
> `
> Thanks,
> - Tyson
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [VOTE] Shorter Attribute Syntax Change

2020-08-18 Thread David Rodrigues
I really found your idea better than all. Keywork is already reserved, make
sense on this context.

Em ter, 18 de ago de 2020 03:49, Aleksander Machniak 
escreveu:

> On 18.08.2020 00:35, Mike Schinkel wrote:
> > 1. Postpone inclusion of attributes until PHP 8.1
>
> +1
>
> I wonder why my suggestion (somewhere in this thread) didn't get any
> attention. Is it because the ship had sailed or it's a terrible idea?
>
> declare(
> SomeAttr,
> AnotherAttr("Hello world")
> )
> function someFunc() {
> }
>
> It's almost identical to #[] or @[], but it looks like PHP and has no BC
> breaks. To me it also sounds good - "declare attribute(s) [for] something".
>
> ps. sorry Mike for a duplicate, I pressed the wrong button.
>
> --
> Aleksander Machniak
> Kolab Groupware Developer[https://kolab.org]
> Roundcube Webmail Developer  [https://roundcube.net]
> 
> PGP: 19359DC1 # Blog: https://kolabian.wordpress.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Import of variables

2020-08-09 Thread David Rodrigues
I suggests to make something like Node does: import "file.php" ($a, $b) so
$a and $b must be extracted from file.php context. All other variables
should be ignored.

Or, to avoid create more complexity and possible new keywords to import
syntax, maybe create a new function:

importx(string $file, ?array $extract = null) and requirex(...) (importx
and requirex is only pseudo)

Em dom, 9 de ago de 2020 11:42, tyson andre 
escreveu:

> Hi Internals,
>
> > This functionality would allow to create a new  'use vars' keyword in
> order to can use( or cannot use )  global variables in local scope( of
> current file ).
>
> To be clear: The variables in the top-level scope depend on what has
> require()d/include()d a file.
> The top-level scope starts off as being global, but if a file is required
> from within a function/method/closure (e.g. the autoloader closure), then
> the top-level scope in the require()'d file uses variables (e.g. $this)
> from whatever context called require().
>
> It may be possible to use a declare syntax, e.g.
> declare(used_variables='all') for `'all'`, `null`, `['var1', 'var2']`, etc.
> - Otherwise, you face the issue of where `use vars` should be allowed,
> what happens if there's a statement before `use vars`, etc.
>
> I can see this as having some use cases, such as in configuration files or
> files used for bootstrapping.
> For example,
>
> ```
>  declare(used_variables=null);
>
> $api_base = IS_PRODUCTION ? 'https://example.com/api/' : '
> http://localhost/api';
> do_stuff();
>
> return [
> // long config array
> 'url_new' => "$api_base/new",
> 'url_all' => "$api_base/all",
> ];
> ```
>
> This feature (ignoring the question of syntax) would ensure that people
> reading the file knew that $api_base was not modified by other files
> and that other files did not read local variables created within a
> configuration/bootstrapping file in unexpected ways,
> which is a fairly common issue in some web apps I've worked on.
> Opcache would also do a better job at optimizing code if it knew which
> variables in a top-level scope couldn't be modified.
>
> That being said, there's been opposition to extensions to the language
> that add functionality that can be implemented in other ways, as in Rowan's
> comment,
> but peoples opinions depend on the specifics of the proposal
> (e.g. `match` was added and was more performant than chained conditionals
> or switch).
>
> As Rowan said, there are ways to reimplement this:
> - Wrapping the config file or bootstrapping file in a closure, global
> function, or class method
> - `function safe_require_once(string $path, $vars = []) { extract($vars);
> require($path); }` from the caller, to limit what variables are passed in.
> IDEs/tooling would be worse at telling you if a file name had a typo,
> though.
>
> Regards,
> - Tyson
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Shorter Attribute Syntax Change RFC 0.2

2020-08-05 Thread David Rodrigues
A new suggestion: @attr(...). It could be used on future for other syntaxes
and should be supersedes the error supression. So will be a BC exclusively
for @attr() error supression for attr() function. But it is few verbose and
easy to understand. With error supression remotion (9.0?) it could be used
for other new features easily.

Em qua, 5 de ago de 2020 13:46, Theodore Brown 
escreveu:

> On Wed, Aug 5, 2020 at 7:20 AM Benjamin Eberlei 
> wrote:
>
> > On Tue, Aug 4, 2020 at 6:37 PM Theodore Brown wrote:
> > > On Tue, Aug 4, 2020 at 8:45 AM Derick Rethans  wrote:
> > >
> > > > Out of Banjamin's suggestion[1], I've updated the Shorter Attribute
> > > > Syntax Change RFC to reflect that process:
> > > >
> > > > https://wiki.php.net/rfc/shorter_attribute_syntax_change
> > > >
> > > > Patches and comments welcome.
> > >
> > > Hi Derick,
> > >
> > > I don't agree with the main argument put forward in this RFC:
> > >
> > > > The main concern is that @@ has no ending symbol and it's
> > > > inconsistent with the language that it would be the only
> > > > declaration or statement in the whole language that has no ending
> > > > termination symbol.
> > >
> > > Attributes are not a standalone statement or declaration; they are
> > > metadata *on* a declaration. They cannot stand alone, but always
> > > modify the following declaration, just as public and static modify
> > > a method, or a type declaration modifies a parameter or property.
> > >
> > > Modifying declarations (e.g. for visibility and type) do not have an
> > > ending symbol. For example, we don't write something like:
> > >
> > > [public] function foo([int] $bar) {}
> > >
> > > With the @@ syntax attributes are treated consistently with type and
> > > visibility declarations:
> > >
> > > @@Jit
> > > public function foo(@@Deprecated int $bar) {}
> > >
> > > So there is nothing inconsistent about not having a termination
> > > symbol - this is in harmony with visibility and type declarations in
> > > PHP, as well as the attribute syntax used by a majority of C family
> > > languages. [1]
> >
> > Attributes are potentially way more complex than a visibility keyword.
> > As such it is a reasonable requirement to say they should have a
> > unified ending symbol, or more broadly speaking that attributes should
> > be enclosed by syntax.
>
> Hi Benjamin,
>
> Yes, attributes that take arguments are more complex than a
> visibility keyword. Union types can also be more complex.
> Nevertheless it is consistent for these declaration modifiers to
> not have an ending symbol.
>
> > It looks nice for a simple attribute like @@Jit, or for a one without
> > arguments like the used @@Deprecated, but as soon as there are more
> > than one, and they each get arguments, enclosing them has its own
> > benefits over them just standing for themselves.
>
> Can you clarify what benefits there are to enclosing them as soon as
> there is more than one attribute with arguments? From my perspective
> this just adds needless complexity without being more concise than
> the @@ syntax.
>
> To me it also looks somewhat strange and less readable to require
> both a closing parenthesis and a closing bracket when an attribute
> has arguments:
>
> #[MyAttr(
> "some value",
> [1, 2, 3],
> namedArg: true,
> )]
>
> # vs.
>
> @@MyAttr(
> "some value",
> [1, 2, 3],
> namedArg: true,
> )
>
> > > When it comes to supporting attribute grouping, I actually consider
> > > this a downside of the #[], @[], and <<>> syntaxes. It complicates
> > > the internal implementation, and makes it so developers have to
> > > choose between two different syntaxes when adding more than one
> > > attribute. In real-world use cases the @@ syntax is just as or even
> > > more concise without the extra parser/compiler complexity:
> > >
> > > #[Attr1, Attr2] # 15 chars
> > >
> > > @@Attr1 @@Attr2 # 15 chars
> > >
> > > # 4 lines, 53 chars not counting whitespace
> > > @[
> > > AttrWithParam("foobar"),
> > > SomeOtherAttr("fizzbuzz"),
> > > ]
> > >
> > > # 2 lines, 52 chars
> > > @@AttrWithParam("foobar")
> > > @@SomeOtherAttr("fizzbuzz")
> > >
> > > I agree that we want the best syntax, not necessarily the best
> > > **looking** syntax. I still believe that the @@ syntax offers the best
> > > balance here. It's familiar, concise without additional complexity,
> > > and doesn't break useful syntax the way @[] and #[] do.
> >
> > Yes, we have been doing this for 20 years, adding annotations enclosed
> > with /** and */ with each enclosing on its own line for the most part.
> > We even added stars in front of every inbetween line.
> >
> > we are stepping into unchartered territory here with @@ by our
> > standards as PHP community. Using "C familiy" as an argument that
> > they made @ work does not mean much, because the language itself is
> > just the "interface" to the implementation, each C

Re: [PHP-DEV] [RFC] Shorter Attribute Syntax Change RFC 0.2

2020-08-04 Thread David Rodrigues
Suggestions:

$(Attribute()) (available)
$[Attribute()] (available)
<> 2)>> (like strings escapes)

About $() syntax:

   - Number of required characters: (2+1)
   - Has end delimiter: yes
   - Allow grouping: yes
   - Forward compatibility in PHP 7: yes
   - Breaks BC of valid PHP 7 codes: no
   - Used by other languages: no?
   - Familiar with Docblock Usage: I don't know
   - Difficulties with Userland Parsers: I don't know

And my another suggestion is use a more verbose for now, until we have a
good consensus about it "using attribute()":

- Number of required characters: (16+1)
- Has end delimiter: yes
- Allow grouping: yes
- Forward compatibility in PHP 7: yes
- Breaks BC of valid PHP 7 codes: no
- Used by other languages: no?
- Familiar with Docblock Usage: I don't know
- Difficulties with Userland Parsers: I don't know


Atenciosamente,
David Rodrigues


Em ter., 4 de ago. de 2020 às 11:03, Benjamin Eberlei 
escreveu:

> On Tue, Aug 4, 2020 at 3:46 PM Derick Rethans  wrote:
>
> > Hi,
> >
> > Out of Banjamin's suggestion[1], I've updated the Shorter Attribute
> > Syntax Change RFC to reflect that process:
> >
> > https://wiki.php.net/rfc/shorter_attribute_syntax_change
> >
> > Patches and comments welcome.
> >
> > FWIW, this has an excemption from the RM Sara as per [2]:
> >
> > > * Shorter Attribute Syntax Change
> > >- Joe/Derick - Please make sure this RFC moves along and reaches
> > >  conclusion by beta3, as discussed previously.
> >
>
> In combination to the existing proposals we already voted one, this RFC
> includes a fourth option that has not been discussed before,
> and could be the compromise we are all looking for :-)
>
> @[Attr] combines both the with to use the familiar @ of many, and the wish
> to have a closing symbol/termination symbol that many others have.
>
> It does not have the downsides that Tyson found w.r.t. to #[Attr] being
> interpreted as comment on PHP 7, but that also means its not forward
> compatible like #[Attr] is.
>
> It provides a small BC break where code written as @[$foo, $bar] = baz();
> or $foo = @["bar" => $baz]; will not compile on PHP 8 anymore, but that can
> be easily
> fixed by writing it with a space between @ and [.
>
>
> >
> > cheers,
> > Derick
> >
> > [1] https://externals.io/message/111218#111261
> > [2] https://externals.io/message/111286#111286
> >
> > --
> > PHP 7.4 Release Manager
> > Host of PHP Internals News: https://phpinternals.news
> > Like Xdebug? Consider supporting me: https://xdebug.org/support
> > https://derickrethans.nl | https://xdebug.org | https://dram.io
> > twitter: @derickr and @xdebug
> >
> > --
> > PHP Internals - PHP Runtime Development Mailing List
> > To unsubscribe, visit: https://www.php.net/unsub.php
> >
> >
>


Re: [PHP-DEV] [RFC] [Discussion] Shorter Attribute Syntax Change

2020-07-30 Thread David Rodrigues
I think that verbosity is not a problem if compared to "strange mixed
symbols", mainly to new users. Google it is a bit hard "what means double
at". And "using attribute" is very clear.

Anyway, I think that is valid we use it for now until we have a good symbol
arrangement, and on future we could have the "verbose syntax" ("using
attribute()") and shortened syntax (to be decided, but like "#[...]").

Atenciosamente,
David Rodrigues


Em qui., 30 de jul. de 2020 às 11:09, tyson andre 
escreveu:

> Hi David,
>
> > I would like to suggests the syntax "using attribute(Attribute, ...)". It
> > is more clear and should not create BC.
>
> I'd agree that it's implementable and works with the tokenizer.
>
> My main objection is the verbosity, which is the reason I assume many
> other languages have fairly short/distinct attribute syntax.
>
> ```
> // Assume Unused tells IDEs/analyzers/linters not to warn about unused
> parameters,
> // and Override warns about a method not being an override
>
> using attribute(Override)
> public function apiMethod(
> using attribute(Unused)
> array $params,
> using attribute(Unused)
> bool $featureEnabled,
> using attribute(Unused)
> array $options,
> ) {...}
> ```
>
> - Tyson


Re: [PHP-DEV] [RFC] [Discussion] Shorter Attribute Syntax Change

2020-07-30 Thread David Rodrigues
I would like to suggests the syntax "using attribute(Attribute, ...)". It
is more clear and should not create BC.

Em qui, 30 de jul de 2020 10:28, Joe Ferguson  escreveu:

> On Thu, Jul 30, 2020 at 7:50 AM Benjamin Eberlei 
> wrote:
>
> > I think it has become clear that we need to revisit this syntax question
> > again, including the elephpant in the room of delaying this feature to
> 8.1.
> >
> > The reason is not only Joe's desire to revote on #[], 
> >
> >
> No, I *do not* want to revote. This RFC simply takes a formal approach to
> approve the syntax that came in 2nd based on concerns raised with the @@
> syntax.
>
> Now that it seems the technical concerns around @@ have been resolved by
> another pending, passing, RFC, I'm still here wanting us to talk about the
> impact of @@ on static analysis tools. Apparently, internals doesn't care
> about these projects. I care and I'm trying to help. I'm not trying to
> revote until I get the vote I want. I'm just a dude that had some free time
> while on vacation when he saw a chance to contribute.
>
> I see two possible outcomes:
>
> Release Managers collectively should decide what we do to move forward.
> Either accept @@, we'll decline this RFC and we can move on to the next
> nearest bikeshed.
>
> OR
>
> If Release Managers don't want to, or can't collectively make a decision
> then this RFC should go to a vote and we'll see what 2/3s of the group
> want.
>
> I'm fine with either outcome.
>
> https://wiki.php.net/rfc/shorter_attribute_syntax_change
>
> --
> - Joe Ferguson
> JoeFerguson.me
> osmihelp.org
>


Re: [PHP-DEV] Allow two words keywords

2020-07-29 Thread David Rodrigues
Oh, you are right! "yield from" is not common for me currently, so I really
skipped it.

In this case, is there some problem to apply it to Attribute case? "using
attribute(Attribute())" or something like that?


Atenciosamente,
David Rodrigues


Em qua., 29 de jul. de 2020 às 14:01, Nikita Popov 
escreveu:

> On Wed, Jul 29, 2020 at 6:50 PM David Rodrigues 
> wrote:
>
>> Hello!
>>
>> I do not know if there is some consensus about "why not use two words as a
>> single keyword" in programming language in general, but I really found a
>> few examples of it, as in SQL with "GROUP BY", for instance.
>>
>> So I question if it could be used on PHP to expand the keywords repertoire
>> by mixing two words without causes BC.
>>
>> I will use the Attribute syntax-war to exemplify.
>>
>> I really prefer to create a new keyword "attr()" or "attribute()" to make
>> attributes possible. It basically uses the same function-like with
>> arguments to work. But it invariably will cause BC to old codes that use
>> attr or attribute names (eg. "function attr()").
>>
>> But, if we create a new two-words keyword like "using attr()", maybe it
>> will not cause any BC, because "function using attr()" is impossible, but
>> "using attr(X) function attr()" will do.
>>
>> I do not know if I am being high with peanuts, but maybe it could be
>> considered to this discussion and make possible new features on PHP
>> without
>> creating strange symbols like @@ or #[] that will requires that new users
>> check the documentation about "what it mean", while is very hard to Google
>> symbols (so search will be "what mean double at in PHP" or "what mean
>> hashtag brackets").
>>
>>
>> Atenciosamente,
>> David Rodrigues
>>
>
> PHP does have a two word keyword: "yield from"
>
> Nikita
>


[PHP-DEV] Allow two words keywords

2020-07-29 Thread David Rodrigues
Hello!

I do not know if there is some consensus about "why not use two words as a
single keyword" in programming language in general, but I really found a
few examples of it, as in SQL with "GROUP BY", for instance.

So I question if it could be used on PHP to expand the keywords repertoire
by mixing two words without causes BC.

I will use the Attribute syntax-war to exemplify.

I really prefer to create a new keyword "attr()" or "attribute()" to make
attributes possible. It basically uses the same function-like with
arguments to work. But it invariably will cause BC to old codes that use
attr or attribute names (eg. "function attr()").

But, if we create a new two-words keyword like "using attr()", maybe it
will not cause any BC, because "function using attr()" is impossible, but
"using attr(X) function attr()" will do.

I do not know if I am being high with peanuts, but maybe it could be
considered to this discussion and make possible new features on PHP without
creating strange symbols like @@ or #[] that will requires that new users
check the documentation about "what it mean", while is very hard to Google
symbols (so search will be "what mean double at in PHP" or "what mean
hashtag brackets").


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] The @@ is terrible, are we sure we're OK with it?

2020-07-23 Thread David Rodrigues
I think that we need some symbol that isn't open-and-close like << and >>,
because it will conflict with shift operation, and basically all
open-and-close options are used for other things; or that confuses with
error suppression like @@ and comments like #[].

Maybe we really need a new keyword, so we can apply it "as a function":
attr(Attribute(), Attribute()) function () {...} or attribute().

Or even more complex syntaxes, like: [: Attribute :].


Atenciosamente,
David Rodrigues


Em qui., 23 de jul. de 2020 às 12:32, Benas IML 
escreveu:

> Just to chime in, `<<...>>` does not have any BC implications or problems
> with bit shift operators.
>
> On Thu, Jul 23, 2020, 6:05 PM Marcio Almada  wrote:
>
> > Hi
> >
> > > On Thu, July 23 2020 at 1:26 AM Mark Randall 
> wrote:
> > >
> > > > On 23/07/2020 02:00, Sara Golemon wrote:
> > > > > Regards the vote; I don't believe that @@ has been proven
> unworkable,
> > > > > however if I'm wrong about that, then the second choice selection
> > from the
> > > > > last vote would obviously take precedence.
> > > >
> > > > I don't believe the concern is that we have something unworkable
> > sitting
> > > > in front of us right now, after all if that were the case we would
> not
> > > > be needing to have this conversation as the RFC would already have
> been
> > > > rendered void.
> > > >
> > > > What we do have, is a deep sense of unease that we collectively made
> > the
> > > > wrong decision, based on, in part, incomplete information.
> > > >
> > > > While the initial block to @@ has been remedied by a larger
> > > > language-level change, that the problem existed at all provided a
> clear
> > > > example of the widely unforeseen challenges associated with the @@
> > > > syntax and its lack of closing tags, and focused renewed attention on
> > > > long-term consequences which where perhaps not given enough
> > > > consideration during the vote.
> > > >
> > > > There has been one occurrence already, there will likely be more in
> the
> > > > future. But what specifically will they be and how severe? We likely
> > > > will not know until they happen.
> > >
> > > Hi Mark,
> > >
> > > I don't agree that there "will likely be more in the future". When I
> > > asked Nikita if he could think of any example that would end up being
> > > a problem, the only one he listed was a infinite parser lookahead
> > > requirement if a) attributes were allowed on statements and b)
> > > generics were implemented with curly braces instead of angle brackets.
> > >
> > > He noted that "it's unlikely we'd actually do that" and ended his
> > > email by saying "it is more likely than not, that we will not
> > > encounter any issues of that nature." [1]
> > >
> > > The @ attribute syntax has been used in other C family languages for
> > > years, and to my knowledge hasn't caused any problems in practice.
> > >
> > > It is actually the <<>> variant that is more likely to back us into a
> > > corner when it comes to future syntax like nested attributes (the RFC
> > > authors considered it to cross a line of unacceptable ugliness,
> > > and the alternative `new Attribute` syntax has technical problems).
> > > This may be one reason Hack is moving away from it to @.
> > >
> > > > But what we can say with reasonable confidence is we have an option
> > > > on the table that is technically superior
> > >
> > > I don't agree that #[] is technically superior. The implementation is
> > > virtually identical. The main practical difference is that hash
> > > comments could no longer start with a [ character, which would be
> > > surprising behavior and a larger BC break (there's definitely code in
> > > the wild using this right now).
> > >
> > > If you have a concrete example of syntax that is *likely* to cause a
> > > problem with @@, please share it. From my perspective, @@ is closest
> > > to the syntax used by the majority of C family languages for
> > > attributes, and thus is *least likely* to present future challenges.
> > >
> > > Best regards,
> > > Theodore
> >
> >
> > I was going to reply these same things, but you beat me to it. But just
> 

Re: [PHP-DEV] The @@ is terrible, are we sure we're OK with it?

2020-07-22 Thread David Rodrigues
My suggestion is the tilde (~). Currently is used only as the bitwise NOT
operator, but in this context seems to not have any problem.

~ Attribute1(~1)
~ Attribute2(...)
function withAttribute() { ... }

Or then we could use another more detailed syntax:

<-- Attribute(...), ... -->
:: Attribute(...), ...

Or even create a new keyword like:

with Attribute(...), ...
function withAttribute() { ... }

And in last case, just use nothing but the attribute itself as a prefix:

Attribute(...) function withAttribute() {...}


Atenciosamente,
David Rodrigues


Em qua., 22 de jul. de 2020 às 10:58, Côme Chilliet <
come.chill...@fusiondirectory.org> escreveu:

> Le Wed, 22 Jul 2020 13:00:10 +0100 (BST),
> Derick Rethans  a écrit :
> > Please, let's do the sensible and use the Rusty #[...] syntax.
>
> This syntax is the one I liked the less in the proposed choices, given # is
>  used for comments.
>
> Wouldn’t #[] cause more parsing issues than @@?
>
> What would be the rule, it’d be illegal to start a comment content with
> '['?
>
> Côme
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC][Discussion] Objects can be declared falsifiable

2020-07-15 Thread David Rodrigues
I really appreciate any effort that can make PHP a more powerful language.
However, for this item, I believe it will generate much greater cognitive
complexity for new users (and I hate to assume that this is a problem, but
we have to remember our roots).

Why, for now a variable $x will be truth, since it is an instance of an
object, now it could be false, because it implements __toBool() and
Falsiable interface in a "magic" way, making everything very confusing if
the user is not aware of each class that he is instantiating (or even
receiving from other places without much condition to know precisely what
it is).

For this type of situation, I still prefer the introduction of clearer
methods that suggest the validation of your own properties, in order to
make it much more flexible than simply returning a single "general" boolean
by-instance. For example: isValid().

if ($entity?->isAdministrator()) { /** Entity is an administrator. */ }
else if ($entity?->isModerator()) { /** Entity is a moderator. */ }
else if ($entity) { /** Entity should be an user or similar. */ }
else { /** Entity is not defined. */ }

On the other hand, the implicity (bool) cast working together with
__toBool() is a good one, but I think that it is being discussed in another
topic.


Atenciosamente,
David Rodrigues


Em ter., 14 de jul. de 2020 às 20:59, Josh Bruce 
escreveu:

> Implement an interface and magic method to allow objects to represent
> false (or empty) while still be valid instances of the custom object (type).
>
> https://wiki.php.net/rfc/objects-can-be-falsifiable <
> https://wiki.php.net/rfc/objects-can-be-falsifiable>
>
> If you saw the latest from this morning, not much has changed except
> hopefully improved formatting and now being the official mix of things.
>
> If this is your first time, the cues are taken from:
>
> - __toString()
> - Stringable
> - and __toArray() (not accepted or approved yet)
>
> Thank you for all the feedback and patience so far, appreciate it!
>
> Cheers,
> Josh


Re: [PHP-DEV] [RFC] \PHP namespace usage heuristics

2020-07-07 Thread David Rodrigues
There are some problem by using double back slash for PHP namespace?

Eg. Instead of \PHP\String be just \\String.

Em ter, 7 de jul de 2020 19:04, Larry Garfield 
escreveu:

> On Tue, Jul 7, 2020, at 4:22 PM, Miguel Rosales wrote:
> > Larry Garfield wrote on 07/07/2020 16:46:
> > > This has reached the 2 week mark, but there's not been much
> discussion.  Anyone else want to weigh in?
> > >
> >
> > I guess I'm missing something obvious here, but the RFC says:
> >
> >  > 5. Component or sub-component namespaces MUST use CamelCase naming
> > conventions.
> >
> > But then in the examples you've got e.g. \PHP\DOM\ or \PHP\SPL\... isn't
> > that incorrect?
> >
> > And slightly related, is there any reason to use \PHP  instead of \Php?
> >
> > Sorry if this has been discussed before, I haven't seen it.
> >
> > Cheers,
> > Miguel
>
> Mm, mainly because I added the CamelCase clause late and didn't think
> about abbreviations.  Whether it should be PHP/XML/DOM or Php/Xml/Dom has
> been an ongoing debate for at least since PHP 5.0.  I have no preference
> strong enough to die on that hill, though, so whatever voters are willing
> to go for I'm good with.
>
> Anyone care enough to offer a bikeshed color?
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Improve "trying to get property 'id' of non-object" error message

2020-07-02 Thread David Rodrigues
Seems great, but maybe include more information should be better:

Warning: Attempt to read property 'property' on bool <> in
/in/IGUcS on line 5


Atenciosamente,
David Rodrigues


Em qui., 2 de jul. de 2020 às 12:27, Máté Kocsis 
escreveu:

> Hi David,
>
> Please have a look at this example code: https://3v4l.org/IGUcS
>
> We've made dozens of error messages more helpful and more consistent
> for PHP 8. This is one of them. :)
>
> Cheers,
> Máté
>


[PHP-DEV] Improve "trying to get property 'id' of non-object" error message

2020-07-02 Thread David Rodrigues
Hello!

Is it possible to improve this error message? It is much more complicated
to identify when we have two occurrences on the same line.

For example:

$availMasterResults->get($availMaster->id . '@' . $sessionUser->id)
-> trying to get property 'id' of non-object

Is not possible to identify if it is related to $availMaster or
$sessionUser variables.

Suggestion:

-> trying to get property 'id' of non-object (null) from variable
$availMaster
-> trying to get property 'id' of non-object (int) retrieved from property
$some->property
-> trying to get property 'id' of non-object (array) retrieved from return
of getObject()


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] [RFC] Property write visibility

2020-06-29 Thread David Rodrigues
With all possibilities maybe we have:

- public set:private unset:private isset:private get:private

set:private could be readed like "set is private".

Where:

- public is "general visibility" for set, unset, isset and get;
- set: affects write visibility;
- unset: affects unset() visibility;
- isset: affects isset() visibility;
- get: affects read visibility;

In this case, maybe we should think on possibility of usage like:

class A {
get:public $x;
}

That determines that $x is private, except by get.

In counterpart, I do not know if it makes sense for isset mode, because if
we have get:public, and $x is accessible, so it is isset by nature.


Atenciosamente,
David Rodrigues


Em seg., 29 de jun. de 2020 às 12:03, Deleu  escreveu:

> As a user, I would prefer the original proposed syntax `public:private` or
> the Swift syntax `public private(set)` than the alternative syntax `public
> int $x {protected set; protected unset;}`.
>
> On Mon, Jun 29, 2020 at 4:22 PM Mark Randall  wrote:
>
> > On 29/06/2020 15:13, André Rømcke wrote:
> > > Would something closer to Swift be better? If so I expanded the RFC
> with
> > > that syntax option as well:
> >
> > Borrowing from the various accessors RFCs:
> >
> > public int $x {
> >protected set;
> >protected unset;
> > }
> >
> > Then a future RFC can build upon it by adding the override functions
> > while keeping the same base syntax.
> >
> > Mark Randall
> >
> >
> > --
> > PHP Internals - PHP Runtime Development Mailing List
> > To unsubscribe, visit: https://www.php.net/unsub.php
> >
> >
>
> --
> Marco Aurélio Deleu
>


Re: [PHP-DEV] Re: [VOTE] Attribute Amendments

2020-06-22 Thread David Rodrigues
I like to suggest that, by default, attributes could be repeatable, so we
can disable this instead (eg. "@@ Attribute(self::IS_UNIQUE)").


Atenciosamente,
David Rodrigues


Em seg., 22 de jun. de 2020 às 13:38, Benjamin Eberlei 
escreveu:

> Hello,
>
> The voting period is over and all four votes have been accepted:
>
> - Rename PhpAttribute to Attribute
> - Allow grouped syntax (though this will probably be obsolete looking at @@
> syntax currently winning the re-vote)
> - Attribute targets
> - Attribute repeatability
>
> Thank you everyone!
>
> On Mon, Jun 8, 2020 at 10:12 AM Benjamin Eberlei 
> wrote:
>
> > Hello internals,
> >
> > I have opened voting for four different amendments to the Attributes RFC
> >
> > https://wiki.php.net/rfc/attribute_amendments
> >
> > The voting period ends at 2020-06-22 8:00 UTC.
> >
> > greetings
> > Benjamin
> >
>


Re: [PHP-DEV] About the use of the terms master/slave and blacklist, proposal to replace.

2020-06-15 Thread David Rodrigues
I don't think that terminology of this type affects people. Or else, they
shouldn't. Comparing "blacklist" with a black person, implying something
pejorative, seems more sick to those who think like that than we actually
understand with the meaning of the word in our midst. I understand that
this can be done in a different way from now on for new codes or updates,
as long as it does not impact immediate understanding and does not create
problems for existing things (like Github wanting to exchange "master" for
"main", which for me will cause much more confusion than actually solving
something for the world).

For me, such changes are just to say "we care" in a very forced and not at
all humble way. They are like youtubers that donate to homeless people just
to get likes, and basically they are not like that at all in everyday life
(of course, considering that there are really exceptions).

Anyway, I believe that we must keep the current terminology as long as it
has specific meaning for us and, if it is to change, to change little by
little, and not in a radical or forced way.


Atenciosamente,
David Rodrigues


Em seg., 15 de jun. de 2020 às 13:15, Daniel Rodrigues Lima <
danielrodrigues...@hotmail.com> escreveu:

> Hi Kalle,
>
> I understand your position.
>
> But i believe that changing retrograde terminologies that refer to bad
> feelings,
> doesn't put us anywhere politically.
>
>
> It's not about sides, it's about people, and our community is made up of
> people.
>
> --
> Cheers,
>
> Daniel Rodrigues
>
> geek...@php.net
> https://twitter.com/geekcom2
>
>
>
> 
> De: Kalle Sommer Nielsen 
> Enviado: segunda-feira, 15 de junho de 2020 12:58
> Para: Daniel Rodrigues Lima 
> Cc: PHP Internals 
> Assunto: Re: [PHP-DEV] About the use of the terms master/slave and
> blacklist, proposal to replace.
>
> Hi
>
> Den man. 15. jun. 2020 kl. 18.43 skrev Daniel Rodrigues Lima
> :
> >
> > Hi internals,
> >
> > I think the time has come for the PHP internals to discuss the use of
> master/slave and blacklist terminologies.
> > As everyone can see, we are going through times of change in the world,
> see #blackLivesMatter for example.
> > Therefore, I propose that we discuss the non-use of terms master/slave,
> because the use of this can allude to the slavery and negative feelings
> about black people.
>
> We are an open source project and should be politically neutral,
> changing this not only causes a huge BC break, but puts us in a
> position where we are no longer politically neutral. You should be
> able to join and be a part of the PHP project without feeling
> obligated to follow certain global politics like trying to not use
> blacklist, master, slave or whatever flavour of the day word here that
> may be offensive to someone.
>
> The moment we change blacklist to blocklist, we are essentially
> agreeing to the fact that we should censor words because they contain
> a color in its name, something that is totally unrelated to any human
> race. Are we also gonna change the internal values of the Garbage
> Collector for PHP to not use different color markings or what about
> the IMG_BLACKMAN filter, are we gonna rename that even though it is
> named so after the Blackman-Turkey transformation? Of course we should
> not. We cannot go around and censor words that have no correlation to
> the current political events occurring world wide. This here is just
> an example of changing things for the sake of changing.
>
> --
> regards,
>
> Kalle Sommer Nielsen
> ka...@php.net
>


[PHP-DEV] Improvement to errors

2020-05-26 Thread David Rodrigues
Hello!

I've been thinking that some errors in PHP are very difficult to
understand. Especially when we use two equal functions with different
arguments on the same line. The error does not make it clear where the
error is.

$strVariable = 'hello';
$nullVariable = null;
return strlen($strVariable) - strlen($nullVariable);

The second strlen() will causes an error: "strlen() expects parameter 1 to
be string, null given - line 107".

So I thought of two possible solutions:

1. Improve the error description, displaying parameters and information
that are easy to reuse (eg. variables).

- "strlen($nullVariable) expects parameter 1 to be string, null given -
line 107"

2. Indicate the offset from where the function was called, along with the
line (which already exists).

- "strlen() expects parameter 1 to be string, null given - line 107:30"

I believe that the second solution is the simplest to be implemented and
already solves the problem enough.


Atenciosamente,
David Rodrigues


[PHP-DEV] Graceful timeout

2020-05-16 Thread David Rodrigues
Hello!

Currently we can use set_time_limit() to specify that our script will run
by some seconds before we get "fatal error: maximum execution time of 1
second exceeded". And we can't catch it and keep running.

I believe that it is interesting to create a function that is able to limit
processing and stop when the time limit is recovered.

$completeRun = set_time_limit_callback(function () {
sleep(2);
}, 1);

var_dump($completeRun);

Where $completeRun will be TRUE only if callback could run until it
returns, and FALSE if timeout.

It should be very useful when we need works with external resources, like
RESTful, where timeout can occur and we need a better way to work with
that. Or when we have few seconds to run a process.

What do you think?


Atenciosamente,
David Rodrigues


Re: [PHP-DEV] Proposal For Return-If / Early Return / Guard Clause Syntax

2020-05-10 Thread David Rodrigues
I just think that this way is more compatible witth the reading. "Return X
if Y" seems better than "return (if) X: (then) Y". Too the ":" could
conflicts with return type.

Em dom, 10 de mai de 2020 16:59, Ralph Schindler 
escreveu:

>
>
> On 5/10/20 1:56 PM, David Rodrigues wrote:
> > Suggestion:
> >
> > return if $x > 1; (to return "void")
> > return $y if ($x > 1 && $x < 5);
> > break if $x > 1;
> > break 2 if $x > 1;
> > throw new Exception if $x > 1;
> >
>
> 100% that will/should be a votable alternative option should this get to
> the voting phase.
>
> I have reasons for why I chose my initial path, but its worth mentioning
> I favor the optional value at the end maybe 65% to 35% where the value
> is after the initial keyword.
>
> Thanks for taking the time!
> -ralph schindler
>


Re: [PHP-DEV] Proposal For Return-If / Early Return / Guard Clause Syntax

2020-05-10 Thread David Rodrigues
Suggestion:

return if $x > 1; (to return "void")
return $y if ($x > 1 && $x < 5);
break if $x > 1;
break 2 if $x > 1;
throw new Exception if $x > 1;



Em dom, 10 de mai de 2020 15:48, Nikita Popov 
escreveu:

> On Sun, May 10, 2020 at 5:49 PM Ralph Schindler 
> wrote:
>
> > Hi!
> >
> >
> > # Intro
> >
> > I am proposing what is a near completely syntactical addition (only
> > change is to language.y) to the language. The best terminology for this
> > syntax is are: `return if`, "return early", or "guard clauses".
> >
> >see: https://en.wikipedia.org/wiki/Guard_(computer_science)
> >
> > Over the past few years, I've seen a growing number of blog posts,
> > conference talks, and even tooling (for example code complexity
> > scoring), that suggest writing guard clauses is a good practice to
> > utilize.  I've also seen it more prevalent in code, and even attempts at
> > achieving this with Exceptions (in an HTTP context) in a framework like
> > Laravel.
> >
> >see abort_if/throw_if:
> > https://laravel.com/docs/7.x/helpers#method-abort-if
> >
> > It is also worth mentioning that Ruby has similar features, and I
> > believe they are heavily utilized:
> >
> >see:
> > https://github.com/rubocop-hq/ruby-style-guide#no-nested-conditionals
> >
> >
> > # Proposal
> >
> > In an effort to make it a first class feature of the language, and to
> > make the control flow / guard clauses more visible when scanning code, I
> > am proposing this in the syntax of adding `return if`.
> >
> > The chosen syntax is:
> >
> >return if ( if_expr ) [: optional_return_expression] ;
> >
> > As a contrived example:
> >
> >  function divide($dividend, $divisor = null) {
> >  return if ($divisor === null || $divisor === 0);
> >
> >  return $dividend / $divisor;
> >  }
> >
> > There is already a little discussion around the choice of order in the
> > above statement, the main take-aways and (my) perceived benefits are:
> >
> >- it keeps the intent nearest the left rail of the code (in
> > normal/common-ish coding standards)
> >
> >- it treats "return if" as a meta-keyword; if must follow return for
> > the statement to be a guard clause.  This also allows a person to more
> > easily discern "returns" from "return ifs" more easily since there is
> > not an arbitrary amount of code between them (for example if the return
> > expression were after return but before if).
> >
> >- it has the quality that optional parts are towards the end
> >
> >- is also has the quality that the : return_expression; is very
> > symmetrical to the way we demarcate the return type in method signatures
> > "): return type {" for example.
> >
> >- has the quality of promoting single-line conditional returns
> >
> >
> > # Finally
> >
> > One might say this is unnecessary syntactic sugar, which is definitely
> > arguable. But we do have multiple ways of achieving this.
> >
> > Of course all of these things should be discussed, I think sub-votes
> > (should this PR make it that far) could be considered.
> >
> > The PR is located here:
> >
> >https://github.com/php/php-src/pull/5552
> >
> > As mentioned, some discussion is happening there as well.
> >
> >
> > Thanks!
> > Ralph Schindler
> >
> >
> > PS: since implementing the ::class feature 8 years ago, the addition of
> > the AST abstraction made this kind of syntactical change
> > proof-of-concept so much easier, bravo!
> >
>
> This proposal looks way too specific to me. I'm a big fan of returning
> early -- but also of throwing early, breaking early and continuing early.
> Supporting this just for returns seems odd / inconsistent to me.
>
> That said, I don't think this syntax solves a real problem in the first
> place. If it solves a problem, it's mostly a problem of PHP coding styles
> being a bit overzealous when it comes to formatting requirements for early
> return/break/continue/throw. And that's not a problem that needs solving at
> the language level...
>
> Regards,
> Nikita
>


Re: [PHP-DEV] max_input_vars trigger detection

2020-05-10 Thread David Rodrigues
Maybe throw an exception by default when it happen. Considering
max_input_vars+1, when hit, throw.

Em dom, 10 de mai de 2020 09:34, Craig Duncan  escreveu:

> >
> > Although not particularly elegant, and it does require you to reject
> requests that hit but don't exceed the limit, I've used this approach
> before:
>
>
> $max = ini_get("max_input_vars") - 1;
> $check = count($_REQUEST);
> if ($check > $max) {
>  throw new RequestException("Request is too large, only {$max} input
> variables are permitted");
> }
>


Re: [PHP-DEV] [DISCUSSION] Match expression

2020-04-13 Thread David Rodrigues
But when we do:

function x() {
   $a = function () { return 123; }
}

We know that "return" here is for the current function () scope, and not
for the parents one. So "return" inside inlined-switch should be used to
specify the switch return itself. Seems clear to me.


Atenciosamente,
David Rodrigues


Em seg., 13 de abr. de 2020 às 12:32, Reindl Harald 
escreveu:

>
>
> Am 13.04.20 um 17:08 schrieb David Rodrigues:
> > With all the humility of the world and without wanting to be exhaustive
> > about this, my only question is why can't we keep it as a switch, instead
> > of creating a new keyword?
> >
> > $x = switch ($y) {
> > case 0: return 1;
> > case 1: return 20;
> > // default: return null;
> > };
>
> because when someone changes behavior where return is expected to return
> from a function/method someone could break his fingers?
>
> return means "stop function or include" and not "stop switch statement"
>


Re: [PHP-DEV] [DISCUSSION] Match expression

2020-04-13 Thread David Rodrigues
With all the humility of the world and without wanting to be exhaustive
about this, my only question is why can't we keep it as a switch, instead
of creating a new keyword?

$x = switch ($y) {
case 0: return 1;
case 1: return 20;
// default: return null;
};

I say this because, in the future, we could do something similar for if():

$x = if ($y instanceof Foo) {
return $y->bar();
} else if ($y instanceof Bar) {
return $y->foo();
}; // else { return null; }

Or even for loopings:

$x = foreach ($items as $item) {
yield $item;
}; // $x == $items

So we would not need to create a new keyword for each equivalent type when
used as an expression.

The only reason would be something like "switch has no return support", but
this could happen exclusively in this scope, just as "use ()" exists only
in functions and not in methods, which are basically the same thing,
however, in different scopes. Likewise, "break 2" would be impossible in
this case, so just issue an error saying "break n is not supported in this
situation".


Atenciosamente,
David Rodrigues


Em seg., 13 de abr. de 2020 às 11:49, Rowan Tommins 
escreveu:

> On 13/04/2020 12:28, Ilija Tovilo wrote:
> >> It would be possible for the blocks to return values (though not with
> >> the return keyword).
> >> [...]
> > We can't do everything at once.
>
>
> Then why not introduce the match expression first, and add block
> expressions (as a general concept) later? That way, we don't need all
> the special restrictions on when to use them, and can work out a
> consistent set of rules for them which can apply language-wide, rather
> than being constrained later by decisions we make half-implementing them
> now.
>
> The ability to use them with short closure syntax would be very
> interesting, if the scoping/capture rules could be agreed.
>
>
> >> it makes *all* the control flow blocks in Rust feel more natural to
> >> developers coming from other languages.
> > Same thing here. If you don't use the result value, it looks just like
> > the switch. That's why I'd feel odd to require a semicolon.
>
>
> Not really. In Rust, it's about making a whole bunch of control
> structures, which are already consistent with each other, more user
> friendly (but still consistent). In your proposal, it's about making one
> specific control structure look slightly more like other syntaxes in the
> same language, by adding a special case which applies nowhere else.
>
> To be specific, in PHP, there is no "omitted semicolon" at the end of
> "if ($x) { y(); }" - that is just how the syntax is defined. There's no
> need to have a parser rule to allow it to look like C or Java, because
> it already does.
>
>
> > This code is parsed like this:
> >
> > ```
> > match($x) { 1 => ['foo', 'bar'] }
> > [0];
> > ```
> >
> > * statement list
> >  * match expr
> >  * array literal
> >
> > Note that we can't have ambiguous grammar since Bison would
> > immediately expose it.
>
>
> I'm not sure what you mean by "we can't have ambiguous grammar" - the
> code above *is* ambiguous, in that it could be defined to mean one of
> two things; what you've shown is which definition your implementation
> defines.
>
> That resolution makes sense for that example, but consider some others:
>
> // As proposed, parsed as two meaningless expression-statements; as a
> normal expression, would select and then invoke a callable
> match($x) { 1 => 'print', 2 => 'var_dump' }
> ($x);
>
> // Invalid under the proposed rule, but a valid method call if match was
> always a normal expression
> match($x) { 1 => new Foo, 2 => new Bar }
> ->doSomething();
>
>
> To be fair, the same limitation exists for closures, where this is invalid:
>
> function($x) { echo $x; } ("Hello");
>
> and you have to write this instead:
>
> (function($x) { echo $x; }) ("Hello");
>
>
> So I guess the above would follow the same rule to force expression
> context:
>
> (match($x) { 1 => 'print', 2 => 'var_dump' })($x);
>
> (match($x) { 1 => new Foo, 2 => new Bar })->doSomething();
>
> The only downside is that omitting the parentheses wouldn't be an error,
> as with the closure case, it would just silently do nothing, which might
> be rather confusing. Dropping the special semicolon handling would mean
> it either did the expected thing or gave a parse error straight away.
>
>
> Regards,
>
> --
> Rowan Tommins (né Collins)
> [IMSoP]
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC][POLL] Switch expression

2020-03-31 Thread David Rodrigues
In relation to "Some people have asked why we don't reuse the syntax of the
switch statement". I do not think that it could cause a conflict with an
array. The same is valid for anonymous functions or classes: you need use
terminator (";"). I still prefer it than create another format to switch.
And maybe you should just use "return" here to specify the return value.

$x = switch ($y) {
case 1: return $y + 1;
case 2: return $y - 1;
// default: return null;
};

Atenciosamente,
David Rodrigues


Em ter., 31 de mar. de 2020 às 15:51, Ilija Tovilo 
escreveu:

> Hi internals
>
> A few days ago I opened the discussion on the switch expression RFC:
> https://wiki.php.net/rfc/switch_expression
>
> There's been a fundamental disagreement on what the switch expression
> should actually be. Due to the conflicting feedback I no longer know
> how to proceed. This is why I've created a poll to get a general
> feeling of what approach is preferred. If you can vote, **please**,
> vote.
>
> https://wiki.php.net/rfc/poll_switch_expression
>
> Ilija
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Feature request - allow to append multiple elements to an array

2020-03-28 Thread David Rodrigues
I think it useful, despite that it could be done by using array_push() as
Woortmann said. Anyway, I think valid a new proposal for thinks like that.

But I will suggests this:

$arr[] = ... $items;


Atenciosamente,
David Rodrigues


Em sáb., 28 de mar. de 2020 às 20:07, Michael Voříšek - ČVUT FEL <
voris...@fel.cvut.cz> escreveu:

> Hi all PHP gurus!
>
> This is a feature request / RFC for the following use-case:
>
> $res = [];
> foreach ($arr as $i) {
> foreach (make_res($i) as $v) {
> $res[] = $v;
> }
> }
>
> Array_merge in loop is very sloop so it is not a solution.
>
> which I propose to shorten to:
>
> $res = [];
> foreach ($arr as $i) {
> $res[...] = make_res($i);
> }
>
> Appending multiple elements to an array is very common use-case.
>
> With kind regards / Mit freundlichen Grüßen / S přátelským pozdravem,
>
> Michael Voříšek


Re: [PHP-DEV] semicolon terminator for switch cases

2020-03-26 Thread David Rodrigues
I agree with Tovilo. It is weird and confusing. Actually I never know that
it was possible. And the ";" sounds like "it ends here", while ":" counds
like "it does it ->". For me, "case 1;" will sounds like "skip case 1".


Atenciosamente,
David Rodrigues


Em qui., 26 de mar. de 2020 às 17:14, Stanislav Malyshev <
smalys...@gmail.com> escreveu:

> Hi!
>
> > Maybe something to deprecate in PHP 8.0.
> > https://wiki.php.net/rfc/deprecations_php_8_0
>
> Why? Whose life it'd make easier?
>
> --
> Stas Malyshev
> smalys...@gmail.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Constructor Property Promotion

2020-03-26 Thread David Rodrigues
Hello!

With all respect, seems a bit confuses to me, without in fact offer a new
feature, just a shortcut. I hope it's me seeing it the wrong way.

What happen if I rename the constructor parameters on a child class
constructor?

Example (https://3v4l.org/VqQde):

class A {
public function __construct(public int $x) { ... }
}

class B extends A {
public function __construct(public int $y) { ...;
parent::__construct($y); }
}


Atenciosamente,
David Rodrigues


Em qui., 26 de mar. de 2020 às 12:45, Sebastian Bergmann 
escreveu:

> Am 26.03.2020 um 14:30 schrieb Nikita Popov:
> > I would like to submit the following RFC for your consideration:
> > https://wiki.php.net/rfc/constructor_promotion
>
> Looks good to me! Thanks.
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Class cast

2020-03-25 Thread David Rodrigues
Hello!

> What's wrong with new Number(123)?

Actually it is a simplest case, where only a single information was
considered. But you can expand it to something more complex, where
currently you will need create a static method to copy the data, which is
not a normalized way like cast could do.

> Not sure why would you want to do this? What's the use case?

You could mix the previous answer when arguments to a method that expects a
Number, for instance: X::test((Number) $x).

Or you can increase the type of information when possible. For instance:

function requiresB(B $b);

But you have only A $a.

You can create:

function __cast($value) {
if ($value instanceof A) return B($value, 123, M_PI);
}

Then use:

requiresB((B) $a);



Atenciosamente,
David Rodrigues


Em qua., 25 de mar. de 2020 às 20:06, Stanislav Malyshev <
smalys...@gmail.com> escreveu:

> Hi!
>
> > 1. Converting from A to B:
> >
> > $a = 123;
> > $b = (Number) $a; // $b is now instanceof Number
> >
> > A instanceof Number will created based on $a value.
>
> What's wrong with new Number(123)?
>
> > 2. Reduce object type (I don't know the technical term):
> >
> > class A {}
> > class B extends A {}
> >
> > $b = new B;
> > $a = (A) $b;
> >
> > $a still is $b, but with "limited" access to A methods and properties.
>
> Not sure why would you want to do this? What's the use case?
> --
> Stas Malyshev
> smalys...@gmail.com
>


[PHP-DEV] Class cast

2020-03-25 Thread David Rodrigues
Currently PHP supports generic castings like (string), (int), ... maybe is
time to allow class castings like (ToClass) $fromObject?

I think that it could be useful to converts to another kind of structure,
or even to reduce object type.

For instance:

---

1. Converting from A to B:

$a = 123;
$b = (Number) $a; // $b is now instanceof Number

A instanceof Number will created based on $a value.

---

2. Reduce object type (I don't know the technical term):

class A {}
class B extends A {}

$b = new B;
$a = (A) $b;

$a still is $b, but with "limited" access to A methods and properties.

---

To make possible custom some kind of castings, I suggests a new magic
method __cast($value).

class Number {
...
function __cast($value) {
if (is_int($value) || is_float($value)) return new static($value);
throw new TypeError();
}
}

Just to talk.


Atenciosamente,
David Rodrigues


[PHP-DEV] Argument with default value

2020-03-14 Thread David Rodrigues
Hello!

I would like to propose the idea of having a keyword that can be used to
use the default value of a parameter, without necessarily having to know
it. Since PHP is not a strong typing language, the default values they use
are quite mixed, and it is difficult to predict each without knowing the
documentation (if you have documented it) or using IDE support.

public function __construct($data = []);
public function __construct($data = null);

I always prefer to use null as the default value to optional parameter, and
then define the value transformation in case it is null. But a lot of
third-party code defines how they want the default value.

String: null or ''
Array: null or []
Integer: null or 0
Boolean: null, true or false

In addition to other values that can actually be used as defaults in a more
specific way.

public function test(int $pi = M_PI, int $a = null, int $b = 0)

My suggestion would be to use the keyword "default" in the context of the
argument. To avoid confusion, another keyword could be created, but I don't
see why they confuse "default" as an argument and "default" for switch.

test(default, 2) === test(M_PI, 2, 0)




Atenciosamente,
David Rodrigues


Re: [PHP-DEV] [RFC] Attributes v2

2020-03-09 Thread David Rodrigues
Another doubt: in relation to the PR (
https://github.com/beberlei/php-src/pull/2) it is called as "attributes",
but seems better keep as "annotations". The Doctrine annotations is based
in PHPDoc, are not? And it is basically the same thing, and annotations
term is used in other languages.

And too, could annotators have some additional features like Typescript
decorators?


Atenciosamente,
David Rodrigues


Em seg., 9 de mar. de 2020 às 16:35, Aleksander Machniak 
escreveu:

> On 09.03.2020 15:42, Benjamin Eberlei wrote:
> > The RFC is at https://wiki.php.net/rfc/attributes_v2
>
> Would it make sense to support this:
>
> <>
> <>
> <>
> function foo() {}
>
> in this form:
>
> <<
> WithoutArgument; // comments allowed here
> SingleArgument(0);
> FewArguments('Hello', 'World');
> >>
> function foo() {}
>
> or if there's not many attributes, in the same line:
>
> <>
>
> It may look better for the short version, but I'm not so sure about the
> long version.
>
> --
> Aleksander Machniak
> Kolab Groupware Developer[https://kolab.org]
> Roundcube Webmail Developer  [https://roundcube.net]
> 
> PGP: 19359DC1 # Blog: https://kolabian.wordpress.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] Re: [RFC] Attributes v2

2020-03-09 Thread David Rodrigues
As I am not a good expert on parser (not to say that I don't do anything),
could you tell me if I can write a note like that?

<<[space]Annotation()[space]>>
<< MyAnnotation(1, 2, 3) >>

It's just because I think the code is more "breathable". Until the PSR
staff decides how best to write.


Atenciosamente,
David Rodrigues


Em seg., 9 de mar. de 2020 às 16:19, Andrea Faulds  escreveu:

> Benjamin Eberlei wrote:
> > I want to resurrect Dmitrys Attributes RFC that was rejected for 7.1 in
> > 2016 with a few changes, incorporating feedback from the mailing list
> back
> > then and from talking to previous no voters.
> >
> > The RFC is at https://wiki.php.net/rfc/attributes_v2
>
> Hi,
>
> I have concerns about these two statements in the RFC:
>
>  > The name of an attribute is resolved against the currently active
> namespace import scope during compilation. The resolved class names are
> then autoloaded to make sure they exist.
>
>  > Consistent with PHP expressions in general, no validation is
> performed if the provided attribute arguments are fullfilling the
> contract of the attribute class constructor. This would happen only when
> accessing attributes as objects in the Reflection API (below).
>
> These two details are inconsistent with eachother: use of an annotation
> triggers an autoload, yet we aren't using the class that is autoloaded
> to validate it? This seems quite wasteful: if we have loaded the class,
> we might as well use it to check the arguments are correct. Also, why
> are we privileging the class existing over the arguments to the class
> being correct? If the arguments can be validated at Reflection time,
> surely the autoloading can be done then too? Both types of coding
> mistake are important.
>
> It also seems inconsistent with existing PHP behaviour, I think normally
> mentioning a class either triggers an immediate autoload and actual
> execution/validation (`new`) or it doesn't (a type declaration). This
> proposal is a strange half-way house.
>
> Is this being done to avoid paying the cost of creating the object at
> compilation time? Because I think triggering the autoload is going to be
> expensive anyway, possibly moreso.
>
> On a different note, the wording here is syntactically ambiguous. It can
> be read as both "if the provided attribute arguments are fullfilling the
> contract […], then no validation is performed" and "no validation is
> performed as to whether the provided attribute arguments are fullfilling
> the contract". I read it as the former the first time, which confused me
> for a moment.
>
> Another thing:
>
>  > Thanks to class name resolving, IDEs or static analysis tools can
> perform this validation for the developer.
>
> Is this referencing the autoloading behaviour? I don't see why that
> would be required. (You could also be referring to the fact you use
> classes, which IDEs can look for, instead of arbitrary string
> attributes, which IDEs can not, which does make sense.)
>
> Thanks,
> Andrea
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] New PCRE function

2020-02-19 Thread David Rodrigues
Maybe you can set all this messages as lowercase? That way we can use it
more easily. If we need the first letter in capital letters we can use
`ucfirst()`, because the opposite is more complicated (a `strtolower()`
would "break" the "JIT" message, for example).


Atenciosamente,
David Rodrigues


Em qua., 19 de fev. de 2020 às 11:37, Nico Oelgart 
escreveu:

> Hi Internals,
>
> I've submitted a small PR proposing a new PCRE function that
> returns a human-friendly string representation of the last error.
>
> https://github.com/php/php-src/pull/5185
>
> Currently there's only preg_last_error() which returns error codes,
> which isn't really helpful. Most comments in the documentation are
> about converting those to something more user friendly.
>
> https://www.php.net/preg_last_error#usernotes
>
> Besides, most extensions provide multiple functions for both
> use-cases natively, such as:
>
>  - json (json_last_error / json_last_error_msg)
>  - socket (socket_last_error / socket_strerror)
>  - sqlite (sqlite_last_error / sqlite_error_string)
>  - ldap (ldap_errno / ldap_error)
>  - etc...
>
> So I think it makes sense for this function to exist.
>
> Any thoughts?
>
> Thank you!
>


Re: [PHP-DEV] Operator overloading for userspace objects

2020-01-28 Thread David Rodrigues
I think that the left operand is the "owner", the magic method handler,
while the right operand is the argument.

So for $object * 5, we will have:

// $object instance
public function __multiply($number): self {
return $this->multiply($number);
}

But for 5 * $object we will have an error. Call order should be respected
now once that will be impossible you have $objectA * $objectB without
defines a priority (the main handler).


--
Atenciosamente,
David Rodrigues


Em ter., 28 de jan. de 2020 às 20:14,  escreveu:

> Hello everybody,
>
>
>
> the last days I have experimented a bit with operator overloading in
> userspace classes (redefing the meaning of arithmetic operations like +, -,
> *, etc. for your own classes).
>
> This could be useful for different libraries which implements custom
> arithmetic objects (like money values, tensors, etc.) or things like
> Symfony
> string component (concatenate) operator, because it improves readability
> much:
>
> $x * ($a + $b) instead of $x->multiply($a->add($b))
>
>
>
> 4 years ago, there was a RFC about this topic (
> <https://wiki.php.net/rfc/operator-overloading>
> https://wiki.php.net/rfc/operator-overloading), which was discussed a bit
> (
> <https://externals.io/message/89967> https://externals.io/message/89967),
> but there was no real Outcome.
>
>
>
> I have tried to implement a proof of concept of the RFC, I encountered some
> problems, when implementing the operator functions as (non-static) class
> members and pass them only the “other” argument: What happens when we
> encounter an expression like 2/$a and how can the class differ this from
> $a/2. Also not every operation on every structure is e.g on commutative
> (e.g. for matrices A*B =/= B*A). So I tried a C#-like approach, where the
> operator implementations are static functions in the class, and both
> arguments are passed. In my PHP implementation this would look something
> like this:
>
>
>
> Class X {
>
> public static function __add($lhs, $rhs) {
>
> //...
>
>}
>
> }
>
>
>
> The class function can so decide what to do, based on both operands (so it
> can decide if the developer wrote 2/$a or $a/2). Also that way an
> implementor can not return $this by accident, which could lead to
> unintended
> side effect, if the result of the operation is somehow mutated.
>
>
>
> I have taken over the idea of defining a magic function for each operation
> (like Python does), because I think that way it is the clearest way to see,
> what operators a class implements (could be useful for static analysis).
> The
> downside to this approach is that this increases the number of magic
> functions highly (my PoC-code defines 13 additional magic functions, and
> the
> unary operators are missing yet), so some people in the original discussion
> suggest to define a single (magic) function, where the operator is passed,
> and the user code decides, what to do. Advantageous is very extensible
> (with
> the right parser implementation, you could even define your own new
> operators), with the cost that this method will become very complex for
> data
> structures which use multiple operators (large if-else or switch
> constructions, which delegate the logic to the appropriate functions). An
> other idea mentioned was to extract interfaces with common functionality
> (like Arithmetically, Comparable, etc.) like done with the ArrayAccess or
> Countable interfaces. The problem that I see here, is that this approach is
> rather unflexible and it would be difficult to extract really universal
> interfaces (e.g. vectors does not need a division (/) operation, but the
> concatenation . could be really useful for implementing dot product). This
> would lead to either that only parts of the interfaces are implemented (and
> the other just throw exceptions) or that the interfaces contain only one or
> two functions (so we would have many interfaces instead of magic functions
> in the end).
>
>
>
> On the topic which operators should be overloadable: My PoC-implementation
> has magic functions for the arithmetic operators (+, -, *, /, %, **),
> string
> concatenation (.), and bit operations (>>, <<, &, |, ^). Comparison and
> equality checks are implement using a common __compare() function, which
> acts like an overload of the spaceship operator. Based if -1, 0 or +1 is
> returned by the  comparison operators (<, >, <=, >=, ==) are evaluated. I
> think this way we can enforce, that the assumed standard logic (e.g
> !($a<$b)=($a>=$b) and ($a<$b)=($b>$a)) of comparison is implemented. Also I
> don’t think this would restrict real world a

Re: [PHP-DEV] register_shutdown_function() not supports private methods

2019-11-28 Thread David Rodrigues
Em qui., 28 de nov. de 2019 às 14:13, Dan Ackroyd 
escreveu:

> On Wed, 27 Nov 2019 at 23:33, David Rodrigues 
> wrote:
> >
> > Hi internals,
> >
> > I am using the register_shutdown_function() inside a class, and then I
> have
> > created a private method to be called during shutdown. I have noted that
> if
> > the method is public it works, but private does not.
> >
> > This shutdown function should be private,
> > to avoid execution at a public scope.
>
> That is one of the reasons Closure::fromCallable was added:
> https://www.php.net/manual/en/closure.fromcallable.php
>
> So like: register_shutdown_function(Closure::fromCallable([$this, 'leave'
> ]));
> Or in your example: https://3v4l.org/MSLA4


Thanks! It will solve the problem.



>
>
> > spl_autoload_register([ self::class, 'privateMethod' ]); // OK
>
> That is not OK. It might not give an error, but it's a bug if a
> private method can be called accidentally, without jumping through the
> deliberate hoops to work around private methods.
>

In that case, it should be deprecated?



>
> Claude Pache wrote:
> > Another workaround is to use a closure:
>
> Although that works, using Closure::fromCallable() has the benefits of
> preserving the parameters and their info.
>
> function foo(int $x) {
> }
>
> $fn = Closure::fromCallable('foo');
> $reflection = new ReflectionFunction($fn);
>
> foreach ($reflection->getParameters() as $param) {
> echo "Param type is: " . $param->getType();
> }
> // Output is "Param type is: int"
>
> cheers
> Dan
> Ack
>


-- 
David Rodrigues


[PHP-DEV] register_shutdown_function() not supports private methods

2019-11-27 Thread David Rodrigues
Hi internals,

I am using the register_shutdown_function() inside a class, and then I have
created a private method to be called during shutdown. I have noted that if
the method is public it works, but private does not.

register_shutdown_function([ self::class, 'privateMethod' ]); // FAIL

Warning: (Registered shutdown functions) Unable to call
MyClass::privateMethod() - function does not exist in Unknown on line 0


In contrast, spl_autoload_register() will works independent if it is
private or public.

spl_autoload_register([ self::class, 'privateMethod' ]); // OK


Example code:

https://3v4l.org/lClJQ

This case is applicable independent if method is static or not.

My real case is that I am initializing a static method that will register
some shutdowns events (that are static methods too). This shutdown function
should be private, to avoid execution at a public scope. As workaround I am
keeping it as public.

So, there are some reason to it do not works like spl does?

-- 
David Rodrigues


[PHP-DEV] Inline switch as alternative to nested inline conditional

2019-10-15 Thread David Rodrigues
Hello. I like to suggests a discussion about a FR to make possible to
inline switch, as an alternative to nested inline conditionals.

$value = switch (expr()) {
case A1: return A2;
case B1: return B2;
default: return C;
}

Instead of:

$expr = expr();
$value = $expr == A1 ? A2 : ( $expr == B1 ? B2 : C );

Just a discussion to check what do you think.

-- 
David Rodrigues


Re: [PHP-DEV] PHP 7.4.0RC3 is available for testing

2019-10-03 Thread David Rodrigues
The release news is buggy.

https://www.php.net/archive/2019.php#2019-10-03-1

Em qui, 3 de out de 2019 às 17:57, Derick Rethans  escreveu:

> PHP 7.4.0RC3 has just been released and can be downloaded from:
>
> <https://downloads.php.net/~derick/>
>
> Or use the git tag: php-7.4.0RC3
>
> Windows binaries are available at: <https://windows.php.net/qa/>
>
> Please test it carefully, and report any bugs in the bug system at
> <https://bugs.php.net>.
>
> Hash values and PGP signatures can be found below or at
> <https://gist.github.com/derickr/4eaedc5dfd3bc9ddfbff6f81e8c53ec1>.
>
> 7.4.0RC4 should be expected in 2 weeks, i.e. on October 17th, 2019.
>
> Thank you, and happy testing!
>
> Regards,
> Peter Kokot & Derick Rethans
>
> php-7.4.0RC3.tar.gz
> SHA256 hash:
> 03f00742fe22767bea22f8c9b9677e05c9fab2b39f931d34e775848fb65aaabf
> PGP signature:
> -BEGIN PGP SIGNATURE-
>
> iQIzBAABCAAdFiEEWlKIB4H3VWCL+BX8kQ3rRvU+oxIFAl2TDxoACgkQkQ3rRvU+
> oxKIFw/+PnimA0hBDXFr71xPOSfWNETDYpf+Qc5/BuPCWa/LblwGfUE7JosQMOQd
> 5h4Ax6aLvCNiLf6s0uJVvOItXICVEfoaIPl/9qlAm6xKb0QpnfEh6dVc7npqLuJW
> KzZ1iBXy3iSHk5RqF45RLlWclehbiSQIBrKuN/S1E4pT07nSSx6IRdSrpWZO8C+a
> 9SSn6kQuddETOL/pX6EthOYO7GtOQSFi4cxsHlYBF+SzHe9CLVVCFek6d+5lURZc
> ebWtN+dKhf43t6AXFnPaYURAPlhquxcfHbv8Vli+8zmsWbGYcljr0voZMFzfv6xg
> qNxLL8b1Eob8XtO0Sah3WyDEVM3l8YN5HVpifyhrCMJRl9GE+u9kh2SVFfXUH+zu
> G1iM6RRNxOp2LmtygAB7I3lN4Ifyo6RIm56n1NrzJXHZpmMWr0RLoaQ0JXha2kcv
> 160FTZlXnGT+fw9v7wG+Zj/NOQ9k7e6nZbpAGzU0EN3AtQY1NcHQf71C2KGYcaxe
> fhuupPoNQ8AHPU3qdGWlruBeQS/eXPyQ9cZQImvtaKtKS2TniFYemuGbKm+bDPm1
> gUD+mMJ1VqUIVp1/J9z+PUTStpRMgWY1Yjlj+6Tcb04NTPd8T3VUiC0xMJ0wtBYA
> p2fIyMn+f9abSGQyRdZZDYX84lz0ArhoJcjbItpFeD16l5Ux+bE=
> =VSAk
> -END PGP SIGNATURE-
>
> php-7.4.0RC3.tar.bz2
> SHA256 hash:
> 594298fba380b6110ba2117ff3efbfd42425dad022fec944ed0a64c05d861918
> PGP signature:
> -BEGIN PGP SIGNATURE-
>
> iQIzBAABCAAdFiEEWlKIB4H3VWCL+BX8kQ3rRvU+oxIFAl2TDx4ACgkQkQ3rRvU+
> oxKJyBAAvh2Zp07vNsqWAUiMWQeBWDQYfQ1x7XF7IWJwMNoRXk3HjfzDWT+svXbR
> gr8pAoYfRagk1/ZdeEHaOk02QFYeOOFVe8yFGrqDEn3y8G/O34UTGr68cXEj/L+x
> AgqPqaIzvHBtrBVfvQ42nYHDwfE/hyU/PrCqNblhy/2mnUBwNl16NQEPmicYeGTz
> X3nZVZTbrzPkKn8osRHJJ9h+9rID+lT629LhQxghz2pRoU61tkwLhoiuOJOXNvl/
> Wgs+7anEeqSbUI+Yx7VpBXFlNDlxeD3p+Jpt1kJzh4PmnmTN5ot7rmvAsAvjlqzE
> IlvjwGda9dlndzbrT2p6frMijxW5JpjEH1QoWgnxiAdmH8MGR6z3QB5RSnPNcKUC
> +YOh4hUS3bph3bL7OO2yGChFuNJ5RCvyukXYdSDXqkvSR4IJhTD7kL/gV5STFWAi
> kVkWYOrfiq/bpbKgWdhcipxCqmZc07cdjmhH/jmnyXWmC+nqV4j21V5rhPWVNWZw
> wDtlg35u+t3ol6VpM+0FRn7xjnYWXSAa5lxa40x4J3PDbuv3yylpAWO/YjYd+BPO
> GLpk7X0E4T9uGy24QzJLv9j3gr0QnlgXbmEajU7cMKkr4AZjxS8fXbcX5JOFtaUj
> WHg4yFfy4Ztock2sXPRiM4p4WmPIovrk8B65QpYc7Ze7h1Aczpk=
> =VCeL
> -END PGP SIGNATURE-
>
> php-7.4.0RC3.tar.xz
> SHA256 hash:
> 0f9aa7a1b42bd9c43895e676fc9383b8392156001e34735e0911c72ae8e81d4a
> PGP signature:
> -BEGIN PGP SIGNATURE-
>
> iQIzBAABCAAdFiEEWlKIB4H3VWCL+BX8kQ3rRvU+oxIFAl2TDx4ACgkQkQ3rRvU+
> oxIw+g/9HB3mS/IuM8HCOsuemSGqK1DPVH0UZdPFNFk3v+iozHuzujLrgGeDsSfW
> eyzUPUzg1RV4ze0FdIVAE6aGTe2VSJxPxBVfhQH6wvdPEuVpBI/JugF91Xj1dFra
> zK1ZtufVSd6Ag5GC2GOrSJJsauZWONyExzUIiFMmElG8TE5my5DFkUnJCbg8IlTB
> wVosRINO/uF5UEeO5/QjquYApiwYoJ9XXXcWOxWFONFwQa2NgvSi6q0nWn4qMFay
> f+sd4L7UXJabSm9bDuuA1px2KKBvRB+brZUVQFMstF0iZthS7s8HWTt7cJt0ITJy
> hDGv8HCWNUMPapr7nqpZckJzAHM4zVmVOp3lfLtCRxCzEqp1LGDoDczcX1Fa3QkL
> DAUUmtKE8b+UUc2u+Qeut/mCukiLUWqMefoxsDnoyO9V/HpWj5SViVka1WfCYwZw
> x5nZqiRRiHEBsCV+qy9YXyog3d7NIoKBRIuTu7/So5DW+JsaQL2oEfmRYev0eNsv
> FYJT/yOj9rPPKpXqASFUb5mwJojT/YGyVRsDliL9cGnGa0AoJU2yQaqskCqmwUDr
> ZDn+LDhhKFVqyY9n1+TwpzyqHZfKTwkom/tbpN7AfQFUv/FIe31MEnRfT2FcvjvF
> RPuF4d5fMZ9AGId2Gp0YgGOaNTu+BZmeB6Q+pnjWNO5fJVRry68=
> =ueur
> -END PGP SIGNATURE-
>
>
> --
> PHP 7.4 Release Manager
> Host of PHP Internals News: https://phpinternals.news
> Like Xdebug? Become my Patron: https://www.patreon.com/derickr
> https://derickrethans.nl | https://xdebug.org | https://dram.io
> twitter: @derickr and @xdebug
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

-- 
David Rodrigues


[PHP-DEV] Symbol implementation

2019-04-27 Thread David Rodrigues
ES6 supports the Symbol type that is a replacement to hard-coded
identifiers where it are not really need.

I like to suggests a similar feature to PHP.

#0: it should be a partial class that could not be instantiated (new symbol
should be invalid, like an abstract class).

In this point I should suggests two options:

1. It should works like a new keyword "symbol", but that could be extended
like a class when need. (It will make sense on item #2). But could be
referenced directly without need of the ::class. (eg. $a = symbol;).

2. Other option is use it as a new keyword "symbol" followed by a \Symbol
reference class (like "instanceof Class" works). Eg. $a = symbol \Symbol;
Anyway, maybe \Symbol could works as a default type, so only $a = symbol
could be do the job. Or even consider symbol as a language constructor,
allowing symbol(\Symbol), for instance.

Ok, now to all make senses (I do expects), keep reading... (I will use
otpion 2 as reference for now)

#1: It could be used to fill constants, for instance, with "magic
identifiers" that have no real value, needly.

Eg.:

public const
USER_NOT_FOUND = symbol(),
USER_INVALID = symbol();

Where USER_NOT_FOUND !=/!== USER_INVALID.

#2: Another possibility is to extends it as an class, so it could be used
as parameter typehint: (not available on ES6, I guess)

class UserErrorSymbol extends \Symbol {}

public const
USER_NOT_FOUND = symbol(UserErrorSymbol),
USER_INVALID = symbol(UserErrorSymbol);

public function setError(UserErrorSymbol $error) {...}

#3: it should have a fallback name (storing a scalar value), so in case you
need to persist it (or serialize), so you could give a name:

public const
USER_NOT_FOUND = symbol(UserErrorSymbol as "UserNotFound"),
USER_INVALID = symbol(UserErrorSymbol as "UserInvalid"),
USER_INVALID_B = symbol(UserErrorSymbol as "UserInvalid");

symbol_alias(USER_INVALID) === 'UserInvalid'
(string) USER_INVALID === 'UserInvalid'
USER_INVALID !=/!== USER_INVALID_B

#4: it could be used as a kind of anonymous array or object key:

$arr[symbol()] = 1;
$arr[symbol()] = 2;
count($arr) === 2

$obj->{symbol()} = 1;
$obj->{symbol()} = 2;
count(get_object_vars($obj)) === 2

But symbol could not be accessed without a valid reference:

echo $arr[symbol()]; // error: index symbol() is undefined or maybe symbol
type could not be used directly to read an array value

$symbol = symbol();
$arr[$symbol] = 1;
echo $arr[$symbol]; // print 1

It is just a draft, but I do belive that it will be a good feature for PHP.


[PHP-DEV] TCO: Tail Call Optimization

2019-04-27 Thread David Rodrigues
Not long ago I heard about the Tail Call Optimization from ES6. It seemed
obscure to me at first, but once I understood the benefit of having it, it
seemed like a good idea of optimization for PHP to avoid recursion problems.

Is there any plan to make it possible in the engine?
-- 
David Rodrigues


[PHP-DEV] Re: [RFC] Nullable Casting

2019-04-21 Thread David Rodrigues
Discussion topic:

- Not 100% needed: is the same that says "nullable typehint is not 100%
need because we can just check in time". This argument has no sense, once
that PHP supports nullable casting for parameters typehint, and the
nullable casting is just a way to fit the argument to parameter typehint
that is already possible, but very hacky ($x !== null ? (string) $x : null
vs. (?string) $x).

- What about e.g. nullable_intval()? intval() is a PHP 4 feature that could
be replaced in 99% of cases by (int) cast. So nullable_intval() make no
sense once that probabily it will be never used (except it (?int) will not
be implemented, but if nullable_intval() could be, so is better (?int)
instead).

- Fallible Casting: it should works exactly as current castings, but with
possibility to be null if it is already null. For instance: (int) "string"
currently will be int (0), by this way, so (?int) "string" should be int
(0) too. The nullable casting will ONLY return NULL if the subject is NULL,
exclusively in this case. So it will affects only (int) null that currently
is int (0). So (?int) null will be null. Same for falsy values: (int) '' is
currently int (0), so (?int) '' will be int (0) also.

- Alternative syntax (null|int): very ugly, no? :P Maybe on future it could
be valid for multicasting eg. (string|int|float) $x, but this is subject to
another topic.

- A cast where you can't be sure of what you'll get back: you will have the
same sure that currently you have with (int) $x, with exception that
nullable values are more explicit because "if $x is null, then you will get
null with 100% of sure". For cases like: (int) 'string', (int) '123string'
and (int) 'string123' what you got? (It is already supported by PHP):
Answer: int (0), int (123) and int (0), respectively.



Em dom, 21 de abr de 2019 às 06:19, Guilliam Xavier <
guilliam.xav...@gmail.com> escreveu:

> On Sat, Apr 6, 2019 at 9:52 AM Guilliam Xavier
>  wrote:
> >
> > Hello internals,
> >
> > David and I would like to open the discussion on our joint RFC:
> >
> > https://wiki.php.net/rfc/nullable-casting
> >
> > Mainly, it would enable to use e.g. `(?int)$x` besides `(int)$x`.
> >
> > We are looking forward to your feedback [...]
> >
> > Thank you,
>
> Hello again internals,
>
> Thanks everyone for your valuable feedback. I have updated the RFC
> with a new Discussion section to [try to] summarize the various
> arguments raised in this thread.
>
> --
> Guilliam Xavier
>


-- 
David Rodrigues


[PHP-DEV] Allow number_format() have three args

2019-04-08 Thread David Rodrigues
Currently number_format() could accept one, two or four args. If three args
is passed then you will receive "wrong parameter count for number_format()"
error (ArgumentCountError).

It have four parameters: float $number, int $decimals, string $dec_point
and string $thousands_sep.

* If one arg is passed, then $decimals = 0 and $thousands_sep = ",".
* If two args is passed, then $dec_point = "." and $thousands_sep = ",".
* If four args is passed, then it will respect given args;

There some cases where we just don't need a $thousands_sep, so I suggest to
accept three args with $thousands_sep = '' (and not a comma).

It will works fine for the doc (
https://www.php.net/manual/en/function.number-format.php) example:

// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', ''); // Currently
$english_format_number = number_format($number, 2, '.'); // After
// 1234.57 (same result)

The fourth parameter will change "the behavior" if compared with the
another original cases, but it will happen because there is no reason to
use three args if you pretends to keep the comma as fourth arg once that
normally you will use or "." or "," as decimal separator.

* If you pretends to use dot + comma, just use two args;
* If you pretends to use comma + dot, just use four args;
* If you pretends to use dot + nothing, use three args;
* If you pretends to use comma + nothing, use three args;

-- 
David Rodrigues


Re: [PHP-DEV] [RFC] Nullable Casting

2019-04-07 Thread David Rodrigues
Real world example:

class Paginator {
// If null, will use the default value (eg. 15), else, it will requires
an int.
public function setItemsPerPage(?int $itemsPerPage) { ... }
}

// Info that came from user input.
// It will be a string, and not a integer, like we need.
$itemsPerPage = Input::get('itemsPerPage');

// If '' then $itemsPerPage = string ''
// If '123' then $itemsPerPage = string '123'

$paginator->setItemsPerPage($itemsPerPage); // Error: expected int, got
string.

Current solution:

$itemsPerPage = Input::get('itemsPerPage') ?: null;
$itemsPerPage = $itemsPerPage !== null ? (int) $itemsPerPage : null;

$paginator->setItemsPerPage($itemsPerPage); // OK

With this new feature: just...

$paginator->setItemsPerPage((?int) Input::get('itemsPerPage')); // OK

Question: why just not check if $itemsPerPage is set like:

$itemsPerPage = Input::get('itemsPerPage');

if ($itemsPerPage) {
$paginator->setItemsPerPage((int) $itemsPerPage); // OK
}

Answer: because in this example we could do that (although the new solution
is much more practical). In another case, I have a static factory method
that depends of an ?int to be created, and I can't just skip it with an
if() if user input is empty.

And about "settype($variable, "?int")" it was requested on original mailing
by Claude Pache.


Em dom, 7 de abr de 2019 às 23:54, Dan Ackroyd 
escreveu:

> On Sat, 6 Apr 2019 at 08:53, Guilliam Xavier 
> wrote:
> >
> > Hello internals,
> >
> > David and I would like to open the discussion on our joint RFC:
> >
> > https://wiki.php.net/rfc/nullable-casting
> >
> > Mainly, it would enable to use e.g. `(?int)$x` besides `(int)$x`.
> >
>
> I'm guessing you don't actually have ths function getIntOrNull() in
> your code-base? To help me understand where this would be useful,
> could you provide some 'real-world' code where this would be useful?
>
> By the way, this RFC is a special case of something that could be far
> more generic. If it was possible to register callbacks to be used when
> casting, people could do something like this:
>
> function castToIntOrNull($value)
> {
> if ($value === null) {
> return null;
> }
>
> return (int)$int;
> }
>
> register_cast_function('?int', 'castToIntOrNull');
>
> $x = (?int)getIntOrNull();
>
>
> > Additionally, it was requested on the mailing list to consider adding
> > support of nullable types to the settype() function,
> > e.g. settype($variable, "?int")
>
> Someone probably needs to make an argument for it to be in core,
> rather than just saying that it's something that could be done.
>
> cheers
> Dan
> Ack
>


-- 
David Rodrigues


[PHP-DEV] random_seed()

2019-03-31 Thread David Rodrigues
Just to know, can we have a random_seed() for random_int()/random_bytes()
like we have mt_srand() to mt_rand()?

I don't know if random_int() is more "random" than mt_rand(), but if it is,
so maybe is valid a random_seed() function.

-- 
David Rodrigues


  1   2   >