Re: [PHP-DEV] [RFC][Vote announcement] Property hooks
Hi, On 12.04.24 04:55, Juliette Reinders Folmer wrote: Hi Ilija, On 12-4-2024 1:00, Ilija Tovilo wrote: Oh, and hang on, they *can* be read from a method in the same class as long as that method is called from within the set hook, so now the method will need to either do a backtrace or use Reflection to figure out whether it has access to the property value. Right. We use the same mechanism as `__get`/`__set` uses to protect against recursion. In particular, when entering a magic method for a particular property, PHP remembers this using a "property guard". It's really just a marker in the object that sets the magic method type, along with the property name. When the same property is accessed again, the magic method or hook is skipped, and PHP behaves as if the magic method or hook wasn't there at all. For `__get`, `__set` and hooks of virtual properties, this means accessing a dynamic property. For backed properties, this means accessing its backing value. After discussing it, we've decided to make virtual properties slightly less surprising by throwing, instead of trying to create a dynamic property. This would be consistent with how virtual read-, and write-only properties are handled outside of hooks, when they are written to or read, respectively. Forgive me, but I had to chuckle at the mention of virtual properties needing to access a dynamic property in the context of a property guard. My thoughts went straight to the following question "Does this mean that support for dynamic properties could never be removed if this RFC gets voted in ? And if so, can we please get rid of the deprecation notice (and need for the attribute) ?" But I see you've already answered that question by changing the behaviour to throw now. ;-) This was something I was confused by as well but wasn't sure at all if this would actually be an issue in a real world. So I tried to come up with a real world example. If I understand correctly you already changed the behavior to throw now but I still want to share anyway Imaging, as library author, you have a property with hooks that contain a typo and you want to rename it in a BC way. Let's say you want to rename "oldProp" to "newProp" but both should work the same as if it would be the same property. class Test { const PREFIX = 'backed:'; public string $newProp { set => $this->prefixize($value); get => $this->getProp(); } public string $oldProp { set { $this->newProp = $value; } get => $this->getProp(); } /** Complex value transformer */ private function prefixize($value) { return self::PREFIX . $value; } /** Complex value reverse transformer */ private function unprefixize($prefixed) { return substr($prefixed, strlen(self::PREFIX)); } private function getProp() { return $this->unprefixize($this->newProp); } } $t = new Test(); $t->newProp = 'foo'; var_dump($t); // object(Test)#1 (1) { ["newProp"]=> string(10) "backed:foo" } var_dump($t->newProp); // string(3) "foo" var_dump($t->oldProp); // string(0) "" $t->oldProp = 'bar'; var_dump($t); // { ["newProp"]=> string(10) "backed:bar" } var_dump($t->newProp); // string(3) "bar" var_dump($t->oldProp); // string(0) "" Kind regards, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
[PHP-DEV] Re: [RFC] [Discussion] [VOTE] Rounding Integers as int
Hi internals, On 17.03.24 13:23, Marc Bennewitz wrote: Hello internals, I have opened the vote for the "Rounding Integers as int" RFC: https://wiki.php.net/rfc/integer-rounding Do to Easter weekend the vote will run for two weeks and two days until Tue the 2nd of April 2024. The RFC has been declined with 18 votes against and 0 in favor. Kind regards, Marc Bennewitz OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] Re: [RFC] [Discussion] [VOTE] Rounding Integers as int
Hi Bob, and sorry for the late reply ... On 19.03.24 01:05, Bob Weinand wrote: Hey Marc, On 18.3.2024 08:53:01, Marc Bennewitz wrote: Hi Bob, On 17.03.24 14:59, Bob Weinand wrote: On 17.3.2024 13:23:04, Marc Bennewitz wrote: Hello internals, I have opened the vote for the "Rounding Integers as int" RFC: https://wiki.php.net/rfc/integer-rounding Do to Easter weekend the vote will run for two weeks and two days until Tue the 2nd of April 2024. Best regards, Marc Bennewitz Hey Marc, I've voted no; it should be just changed without any force_float parameter. Just always return int when possible (and the input was int). If users wish to have the old behaviour, they should just explicitly cast via (float). The effective BC break of that would be quite small if some things which return float today now would return int. I cannot imagine many cases where this would actually be unwanted. And as said, explicit (float) casts are always possible. I also dislike force_float, as it cannot just be added to a function in any code which shall be backwards compatible to 8.3 and older. It would just emit Uncaught Error: Unknown named parameter $force_float. Changing the return type from float to int is a non trivial quite hard to find behavior change. Imaging code like this: $x = 800; $y = 800; round($x/$y) === 1.0; This will return false instead of true especially because we teach users to use strict comparison. Such behavior change should be done in a major version. I see, here we disagree: - Strict comparison should be avoided when working with numbers. Strict comparisons are generally for strings and booleans. - There's no reason to artificially wait years here. Agree, strict comparison should be avoided when working with numbers but this detail normally does not get mentioned if an "equal vs. same" discussion comes up and there are even coding styles out there forcing users to use strict comparison everywhere like - https://github.com/slevomat/coding-standard/blob/master/SlevomatCodingStandard/Sniffs/Operators/DisallowEqualOperatorsSniff.php - https://github.com/laminas/laminas-coding-standard/blob/2.6.x/src/LaminasCodingStandard/ruleset.xml#L659 With the additional parameter it's possible to opt-in into the new behavior already in 8.4 while in PHP 9.0 the default behavior will change but previously opted in code does not need to get touched again. Just changing the behavior means waiting for PHP 9.0 without a way to opt-in in 8.4 already. If you are not interested in opting in in 8.4 already you can just ignore the additional argument as this will be the default in 9.0. I'm not interested in having an additional parameter I have to carry forward for quite some years. To mimic the previous behavior in a fully BC way it's as simple as explicitly casting the value to float. I would rather have preferred to see a static analysis solution how often round()ed results are compared strictly, assess the actual BC impact and possibly encourage tools like Rector to recognize such patterns. As of the above reason and because the rounding functions are very highly used functions I think it's obvious that such behavior change will break a lot of code out there. I'm a bit confused because normally possible BC breaks have to be avoided as much as possible and if a feature is ranked higher it still needs to smooth migration but here it seems to me now it's fine to break a lot of users code without warning and without a way to opt-in before (which was requested previously). Bob Regards, Marc Bob OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] Re: [RFC] [Discussion] [VOTE] Rounding Integers as int
Hi Vincent, On 17.03.24 22:59, Vincent Langlet wrote: Hi, IMHO, the more meaningful cases of the RFC are missing : round(float, precision: >= 0): int|float // only cast to float for int overflow ceil(float): int|float // only cast to float for int overflow floor(float): int|float // only cast to float for int overflow Calling ceil or floor on integer is meaningless, because it will return the same value. The RFC should be "Prefer int as return value when possible". I do believe it's important to avoid unnecessary casts as much as possible and leave it up to the user making cast explicit than implicit else the behavior gets quite unpredictable. Implicitly casting to float only happens on int underflow/overflow. Implicitly casting to int will never happen. As you say "Calling ceil or floor on integer is meaningless, because it will return the same value." this is already noted in the RFC and the functions will be a no-op in this case. Best regards, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] Re: [RFC] [Discussion] [VOTE] Rounding Integers as int
Hi Bob, On 17.03.24 14:59, Bob Weinand wrote: On 17.3.2024 13:23:04, Marc Bennewitz wrote: Hello internals, I have opened the vote for the "Rounding Integers as int" RFC: https://wiki.php.net/rfc/integer-rounding Do to Easter weekend the vote will run for two weeks and two days until Tue the 2nd of April 2024. Best regards, Marc Bennewitz Hey Marc, I've voted no; it should be just changed without any force_float parameter. Just always return int when possible (and the input was int). If users wish to have the old behaviour, they should just explicitly cast via (float). The effective BC break of that would be quite small if some things which return float today now would return int. I cannot imagine many cases where this would actually be unwanted. And as said, explicit (float) casts are always possible. I also dislike force_float, as it cannot just be added to a function in any code which shall be backwards compatible to 8.3 and older. It would just emit Uncaught Error: Unknown named parameter $force_float. Changing the return type from float to int is a non trivial quite hard to find behavior change. Imaging code like this: $x = 800; $y = 800; round($x/$y) === 1.0; This will return false instead of true especially because we teach users to use strict comparison. Such behavior change should be done in a major version. With the additional parameter it's possible to opt-in into the new behavior already in 8.4 while in PHP 9.0 the default behavior will change but previously opted in code does not need to get touched again. Just changing the behavior means waiting for PHP 9.0 without a way to opt-in in 8.4 already. If you are not interested in opting in in 8.4 already you can just ignore the additional argument as this will be the default in 9.0. To mimic the previous behavior in a fully BC way it's as simple as explicitly casting the value to float. Bob Regards, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] Re: [RFC] [Discussion] [VOTE] Rounding Integers as int
On 17.03.24 14:10, Tim Düsterhus wrote: Hi On 3/17/24 13:23, Marc Bennewitz wrote: I have opened the vote for the "Rounding Integers as int" RFC: https://wiki.php.net/rfc/integer-rounding Please also update the Status within the RFC itself and move it to the correct section in the RFC overview at: https://wiki.php.net/rfc Thank you for the reminder. Updated the status and moved in correct section now. Best regards Tim Düsterhus OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
[PHP-DEV] [RFC] [Discussion] [VOTE] Rounding Integers as int
Hello internals, I have opened the vote for the "Rounding Integers as int" RFC: https://wiki.php.net/rfc/integer-rounding Do to Easter weekend the vote will run for two weeks and two days until Tue the 2nd of April 2024. Best regards, Marc Bennewitz OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Larry, On 10.03.24 16:52, Larry Garfield wrote: On Sun, Mar 10, 2024, at 10:31 AM, Gina P. Banyard wrote: On Saturday, 9 March 2024 at 16:00, Larry Garfield wrote: I am still opposed to this. Logically, ceil/float/round should be returning ints, not floats. Only returning ints if it was given an int is, er, kinda pointless, as you'll just get back the value you passed in. (Because it's already rounded/floored, etc.) So this doesn't get us any new type safety, but does make the return type less consistent than it is today. That's a step backwards. If there's some math reason that we cannot have those functions return int (someone mentioned there was, but I don't really understand it and the RFC does not explain it at all), then we should at least keep consistency in the return type. "Sometimes I have to cast the return value before I can actually use it in the obvious way, sometimes I don't" is not a good situation. --Larry Garfield There are plenty of values that are exactly representable as floating point numbers but not as integers. One short example: $v = 1e10 + 0.6; var_dump($v); var_dump(round($v)); Gives you accurate precision and proper rounding behaviour. 1e10 *cannot* be represented as an integer. So round *must* be able to return a float. Best regards, Gina P. Banyard Please include some version of this in the RFC. Especially if it can be even more detailed. --Larry Garfield While float's get imprecise on represent integers > 2^53, int's can't represent such a bit range of numbers as floats can. On rounding a floating point number your already have to deal with the imprecise of floats in the first place. That's why rounding operations should take the input type into account and only cast if the input type can't represent the resulting number to avoid ending up in overflow or error. In case you where looking at python where round() is documented with ... > The return value is an integer if /ndigits/ is omitted or |None|. Otherwise, the return value has the same type as /number/. ... but in python int is limited only by memory and not by the type which makes it very different. I have added a description and updated example in the RFC. Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi all, I now have updated the RFC to allow to opt-in to new behavior on PHP 8.4 and be able to opt-out to previous behavior in PHP 9.0 via new parameter "force_float". Also the deprecation has been removed as nobody liked it. Best regards, Marc On 26.09.23 12:39, Marc Bennewitz wrote: Hi internals I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC][Discussion] Raising zero to the power of negative number
Hi Jorg, On 13.01.24 00:25, Jorg Sowa wrote: Thank you for the suggestions. I agree that error message should be more meaningful. I changed it. The main driver of this change is to match the division by zero behavior for both operators which can operate on both integers and floats. Would it make sense to create a function `fpow` similarly to `fdiv` for the correct IEEE 754 logic? As of your note of consistent behavior here, in your RFC I don't see any note about operating on float - It's all about int. It would be good to explicitly describe both int and float behavior in your RFC. About `fpow` - I personally never felled the need to use `fdiv` but as `fdiv` was explicitly introduced to expose IEEE-754 semantics I think it totally makes sense to add `fpow` as well. Greetings, Marc Kind regards, Jorg OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC[ Property accessor hooks, take 2
Hi Larry, first of all thank you very much for this amazing work you two have been done :+1:. On 23.02.24 00:56, Larry Garfield wrote: On Wed, Feb 21, 2024, at 11:02 PM, Matthew Weier O'Phinney wrote: On Wed, Feb 21, 2024 at 12:57 PM Larry Garfield wrote: After much on-again/off-again work, Ilija and I are back with a more polished property access hooks/interface properties RFC. It’s 99% unchanged from last summer; the PR is now essentially complete and more robust, and we were able to squish the last remaining edge cases. Baring any major changes, we plan to bring this to a vote in mid-March. https://wiki.php.net/rfc/property-hooks It’s long, but that’s because we’re handling every edge case we could think of. Properties involve dealing with both references and inheritance, both of which have complex implications. We believe we’ve identified the most logical handling for all cases, though. Once again in reading the proposal, the first thing I'm struck by are the magic "$field" and "$value" variables inside accessors. The first time they are used, they're used without explanation, and they're jarring. Additionally, once you start defining the behavior of accessors... you don't start with the basics, but instead jump into some of the more esoteric usage, which does nothing to help with the questions I have. So, first: - Start with the most basic, most expected usage for each of reading and writing properties. - I need a better argument for why the $field and $value variables exist. Saying they're macros doesn't help those not deep into internals. As a user, why do they exist? For $field, it's not a requirement. It's mostly for copy-paste convenience. A number of people have struggled on this point so if the consensus is to leave out $field and just use $this->propName directly, we can accept that. They can be re-added if reusable hook packages are added in the future (as noted in Future Scope). I'm also feeling that introducing magic variables isn't the best design choice. I read your section about "Why do set hooks not return the value to set?" and I don't really agree. Let me explain ... 1. Virtual properties and technically all functions return a valid. I think it would me much less magic if property setters on virtual properties declare a void return type. This would make it very obvious that this is a virtual property even on having to read complex setters. 2. it disallows any action /after/ the assignment happens I actually think this would be a good think! An object property should only be set after everything has been done. If you want to do more it should either not be part of the setter or you should use a temporary variable what you have to do anyway to not leave your object in an incorrect state. Let's say we have the following setter: public string$name { set($value){ // do stuff $field = $value; // or $this->name = $value // do more stuff and (eventually) fail throw Exception(); } } try { $object->name = 'test'; } finally { $object->name; // what is name here ? } 3. ambiguity I actually feel that $field is ambiguous. What happens if you declare `set($field) {}` ? Does such construct let the engine set the property value immediately as the input value gets immediately assigned to the property via $field? Greetings, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] Requesting RFC karma
On 20.02.24 09:58, Derick Rethans wrote: On 20 February 2024 08:41:19 GMT, Marc Bennewitz wrote: Hi Hans, On 16.02.24 13:05, Hans Henrik Bergan wrote: My name is "Hans Henrik Bergan", usually go by the nickname "divinity76", I've contributed to OSS (including PHP) for years, and am currently involved in 3 things that might require an RFC, and requesting RFC karma for wiki account "divinity76". 3/3: int|float for DateTime::setTimestamp, setTimestamp(0.123456) => 1970-01-01 00:00:00.123456 :https://github.com/php/php-src/pull/13383 Actually I also want to work on this if I find time ... but as this is a BC break I think it makes sense to revisit DateTime (and friends) to bundle BC breaks to a single PHP version - probably PHP 9 and more sure there is a way for users to make it work in PHP (7+)8+9. Personal and incomplete list I think needs improvements: * allow float for `setTimestamp` * option to return timestamp as float to simplify passing it to JS * Missing getter/setter for most of the date/time parts like `get/setSecond`, `get/setHour` etc. * For now I only added `get/setMicroseconds` together with `createFromTimestamp` because `DateTime::createFromTimestamp(123456789)->setMicroseconds(123987)` * After thinking about naming - I think this should be renamed to singular * Add missing methods to DateTimeInterface * Allow userland implements DateTimeInterface * Define how `createFromInterface` behaves on userland implementations * fixing ISO 8601 format * fixing some return type definitions from self to static * strict mode * `DateTime::createFromFormat('Y-m-d', '2023-02-29')` * `DateTime::createFromFormat('Y-m-d H:i', '2024-03-31 02:30', new DateTimeZone('Europe/Berlin'))` * Missing current microseconds on `createFromFormat` but other non defined parts needs to be explicitly reset using `|!` * leap seconds support on UTC TZ * As of leap seconds ... wouldn't it be better to default to +00:00 instead of UTC ? * Support nanoseconds I'm for sure not able to work on all these points and that's why I only started very small close to no BC improvements without RFC. Marc IMO, doing tweaks to this base functionality isn't the way forwards. I've been having on and off conversations with Florian over the last couple of months to see if we can design a better higher level API instead of patching the nits. Do you mean adding an additional API in C or userland? Is there a way to participate on the discussion? cheers Derick Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] Requesting RFC karma
Hi Hans, On 16.02.24 13:05, Hans Henrik Bergan wrote: My name is "Hans Henrik Bergan", usually go by the nickname "divinity76", I've contributed to OSS (including PHP) for years, and am currently involved in 3 things that might require an RFC, and requesting RFC karma for wiki account "divinity76". 3/3: int|float for DateTime::setTimestamp, setTimestamp(0.123456) => 1970-01-01 00:00:00.123456 : https://github.com/php/php-src/pull/13383 Actually I also want to work on this if I find time ... but as this is a BC break I think it makes sense to revisit DateTime (and friends) to bundle BC breaks to a single PHP version - probably PHP 9 and more sure there is a way for users to make it work in PHP (7+)8+9. Personal and incomplete list I think needs improvements: * allow float for `setTimestamp` * option to return timestamp as float to simplify passing it to JS * Missing getter/setter for most of the date/time parts like `get/setSecond`, `get/setHour` etc. * For now I only added `get/setMicroseconds` together with `createFromTimestamp` because `DateTime::createFromTimestamp(123456789)->setMicroseconds(123987)` * After thinking about naming - I think this should be renamed to singular * Add missing methods to DateTimeInterface * Allow userland implements DateTimeInterface * Define how `createFromInterface` behaves on userland implementations * fixing ISO 8601 format * fixing some return type definitions from self to static * strict mode * `DateTime::createFromFormat('Y-m-d', '2023-02-29')` * `DateTime::createFromFormat('Y-m-d H:i', '2024-03-31 02:30', new DateTimeZone('Europe/Berlin'))` * Missing current microseconds on `createFromFormat` but other non defined parts needs to be explicitly reset using `|!` * leap seconds support on UTC TZ * As of leap seconds ... wouldn't it be better to default to +00:00 instead of UTC ? * Support nanoseconds I'm for sure not able to work on all these points and that's why I only started very small close to no BC improvements without RFC. Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] Custom object equality
Hi Jordan, On 23.10.23 22:07, Jordan LeDoux wrote: Implementing the compare handler for an overload requires adding two new entries to ZEND_AST_BINARY_OP because the `>` and `<` comparisons have to be preserved in the AST in order to call the correct object handler. THAT requires updating OpCache and JIT since all such comparisons are currently reordered to use `<`, and though I spent quite a while looking at it, I think Dmitry might be the only person that could really implement that fully. At least, I never found anyone that had the expertise to actually help me with it. 17 years ago Sara was working on it, too ;) https://externals.io/message/21883 Jordan Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi, On 26.09.23 12:39, Marc Bennewitz wrote: Hi internals I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding Best, Marc Based on the discussion I see two groups. The one that would like to change this behavior without message (bug fix) and others that see a to big BC break never willing to touch it at all. On the same time my current approach of finding a compromise by introducing an upcoming behavior change as deprecation message doesn't make anyone happy. This makes me go back and collect other ideas: 1. Argument $force_float * $force_float=true in PHP 8.4 + deprecation on passing int and omitting this new argument * $force_float=false in PHP 9.0 This allows to opt-in new behavior asap, warns about upcoming behavior change on passing integers and allows a clean way to fix the deprecation. But do we would like to keep this argument forever? If not it requires another deprecation phase forcing people again to fix deprecation messages. Would it be more logical for `$force_float=false` to return the best possible mathematical correct value instead of trying to keep the input type if possible? Means a float input could also be cast to int if int is a better fit in this case. 2. Integer specific function * round_int This also would allow opt-in proposed behavior without BC break. But this comes with a couple of downsides: * Does not improve out-of-the-box behavior * Requires type-checks before opt-in and goes against PHP as a loosely typed language * New inconsistency on function naming `round` vs. `round_int` - or just another alias * New questionable behavior - Why does `round_int` return a float in some cases? Or should this be an error now? * No logical ceil/floor variant - using these requires type-checks to not loose integer precision For me this is a no-go, I wouldn't vote for it and obviously wouldn't propose this in my own RFC. 3. Any other ideas for making all happy? Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Jakub, On 16.10.23 00:17, Jakub Zelenka wrote: Your JSON example is a bit unrelated because if you care about your types your should have used JSON_RESERVE_ZERO_FRACTION in the first place else you should not care about int vs float at all. The thing is that JSON might be encoded by another application that doesn't care about types that much. In fact in JSON there is no difference between 2.0 and 2. So this is quite possible situation IMHO. That's obviously true but on the same time you should validate and filter your input data. And if you expect a floating point number you need to handle that case explicitly before processing and not leave it to an implicit transformation just hoping everything will be fine. It's true that passing/returning int to/from a function expecting float will cast but currently with these rounding functions it's a different deal as they expect an `int|float` instead of just `float`. So it's not cast on passing the argument but the functions itself are casting. Well internally yeah but effectively it is a cast on the return type. What I meant is that this wont help everywhere when it's passed to function expecting just float unless it is changed by user to accept int|float. Where another set of functions would avoid the BC break it also would be against having PHP as a loosely typed languageputting the burden to everyone caring. I already see hundreds of `is_int($v) ? round_int($v) : round($v)` everywhere around. But for me it's sort of an edge as I would think it is not that usual rounding values that are greater than 2^53. I think it would be good to note in the RFC what other language do about this issue. I quickly checked Go and it seems to only have float64 rounding (Math.Round). Rust seems to also round just f64. At least python's build-in round function keeps the input type, as long as ndigits is given, else it even goes further and returns an int. I'm starting to feel that the problem is that the input type is defined as int|float. I think we should just correct it to float. With the current behavior ... yes, but this does not make these functions any better. Sure, I'm trying to improve a case for that does not happen often, but it happens at least for me on working with representing statistical data where using GMP/bcmath ... does not outweigh it's overhead. On the same time the results can be improved without adding overhead. Regards Jakub Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Robert, On 13.10.23 13:44, Robert Landers wrote: On Fri, Oct 13, 2023 at 1:26 PM Jakub Zelenka wrote: On Tue, Sep 26, 2023 at 11:39 AM Marc Bennewitz wrote: Hi internals I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding I would personally prefer a new function for rounding integers if anyone wants to round large integers. The things is that the current round behaviour is consistent with a way how floats to int conversion is done for strict types. Just to add some nuance, if you are going anywhere near the edges of ints (e.g., custom encryption prototypes from papers), you generally know that will happen -- it's math and pretty easy to verify. In those cases, you likely will be using GMP or some other extension to handle the large numbers. The point is, I highly doubt people are unknowingly using round() with exceptionally large numbers. If they are doing so, they probably know exactly what they are doing and already handle all potential edge cases or they use an extension specifically for dealing with large numbers. This very much depends on where you define your edges. Basically we are talking about 2^53 to 2^63 which is 1024 times higher number. Forcing people into such extensions much earlier than necessary isn't very helpful either as they all come with it's own downsides as well. Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Jakub, On 13.10.23 13:25, Jakub Zelenka wrote: On Tue, Sep 26, 2023 at 11:39 AM Marc Bennewitz wrote: Hi internals I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding I would personally prefer a new function for rounding integers if anyone wants to round large integers. The things is that the current round behaviour is consistent with a way how floats to int conversion is done for strict types. Your JSON example is a bit unrelated because if you care about your types your should have used JSON_RESERVE_ZERO_FRACTION in the first place else you should not care about int vs float at all. It's true that passing/returning int to/from a function expecting float will cast but currently with these rounding functions it's a different deal as they expect an `int|float` instead of just `float`. So it's not cast on passing the argument but the functions itself are casting. Where another set of functions would avoid the BC break it also would be against having PHP as a loosely typed languageputting the burden to everyone caring. I already see hundreds of `is_int($v) ? round_int($v) : round($v)` everywhere around. If you really want to make such change to round, then I would be prefer targeting just 9.0 without any deprecation as I don't think the deprecation should be informational only and not fixable in the code. Cheers Jakub Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Tim, On 05.10.23 21:57, Tim Düsterhus wrote: Hi On 10/4/23 08:35, Marc Bennewitz wrote: As far as I understand you are in favor of option 1. (considering it a bugfix) but how do you make sure this will not lead to different application behavior overlooked on upgrading? Also there is no way to opt-in new behavior. Yes, I would be in favor of option 1 and I don't even see a reason not to do this in PHP 8.4 right away. As I mentioned before, this effectively can be considered a bug fix: PHP does not correctly round integers > 2^53. While this is not a bug fix that is appropriate for the current stable branches, I don't see why it would not be appropriate for PHP 8.4 if there's an RFC for it. In fact there is already a rounding bugfix (no RFC for that) in PHP 8.4: https://github.com/php/php-src/blob/65a8c70f93ccb7e008de147cd4c357681c653bd0/UPGRADING#L75-L82 While PHP tries hard to keep backwards compatibility within a given major, keeping full compatibility is effectively impossible for the huge API surface PHP exposes. Every version includes *some* changes that are technically breaking for one reason or another. Fixing edge cases like having 0.49994 rounded down correctly is a different story than having something simple like "round(10 / 2) === 5.0" to return false instead. Best regards Tim Düsterhus Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi George, On 05.10.23 14:12, G. P. B. wrote: On Thu, 5 Oct 2023 at 07:40, Marc Bennewitz wrote: I don't see a bug or broken behavior here as these functions were processing floating point numbers since forever. https://3v4l.org/PrrmO That's not my point, the point is about the function being broken for large 64bit integers, which your RFC is fixing. I would also expect most people that actually use ceil/floor/round to dump the return value of it into a property/value that is expected to be an int. Which is also compatible for floats that fit in an int (and since 8.2 for those that have a fractional part a warning is emitted). I see no benefit in doing this weird approach instead of just changing the behaviour. Yes this is a theoretical BC break [1], but unless you can show me an actual use case that breaks (and even then) I don't think the approach of this RFC is good. Running a quick code search /round\([^\(]+\)\s===/ language:PHP on GitHub finds possible breakages based on strict comparison: // if width and height are ints $x = ( $height1 / $width1 ) * $width2; if ( round( $x ) === round( $height2 ) ) { // if number is int public static function isZero($number, $precission = 2) { return round($number, $precission) === 0.0; } // where ecb is int return $ecb && round(5000 / $ecb) === 2.0; George P. Banyard [1] And this is coming from me, who does love finding weird edge cases and remove them from the language, just look at the 8.3 range() RFC OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
On 05.10.23 01:38, G. P. B. wrote: On Tue, 26 Sept 2023 at 11:39, Marc Bennewitz wrote: Hi internals I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding I don't understand the point of the deprecation phase at all. Frankly, I consider this RFC a bug fix of the current "broken" implementation, which was broken with 7.0 and the move to 64bit integers. As such, I would just make the behaviour of returning integers the default behaviour in 8.4. If, for some weird reason, people want less accurate numbers, they can always cast the input to float. I don't see a bug or broken behavior here as these functions were processing floating point numbers since forever. https://3v4l.org/PrrmO Best regards, George P. Banyard Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature.asc Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi, On 03.10.23 14:41, Tim Düsterhus wrote: Hi On 9/30/23 08:26, Marc Bennewitz wrote: The deprecation would act as an information for upcoming behavior change, not classical deprecation of future removal. If the new behavior is what you want, than you don't need to change anything as a deprecation message should not break anything. At the same time people Correct, the deprecation message itself would not break anything. However when the new behavior is the behavior I desire, it would: 1. Cause noise in my logs, because the deprecation would continue to be emitted until the behavioral change is finally implemented. 2. Be confusing when working in preparing my application for future PHP versions by handling all deprecations. The only solutions would be either adding an '@' in front of every call to round, ceil, floor (which might suppress additional errors I *do* care about) or ignoring this specific deprecation within the error handler of the application after verifying that I checked all locations for correctness. There is no way for me to reliably mark only this specific deprecation as acknowledged / handled for a specific place within my code. This also extends to library developers who are already under pressure by users to make their libraries deprecation free on or before the release of a new PHP version. As the library doesn't control the error handler, they can't just ignore this specific deprecation for their library, without casting the input to float, despite being happy with the new behavior that will arrive in PHP 9. In other words, this deprecation is not really actionable to me as a developer, because I can't migrate to the new behavior on my own pace. I do understand and I agree that it's not optimal but the issue is the lack of good alternatives. I only see three possible ways and all of them are suboptimal: 1. Don't trigger upcoming behavior change message (deprecation message) * impossible to opt-in new behavior in 8.4 * This could lead to different application behavior overlook on upgrade to 9.0 2. trigger upcoming behavior change message without possibility to opt-in new behavior (as proposed) * impossible to opt-in new behavior in 8.4 * either force old behavior or noise in logs 3. introduce new argument * possibility to opt-in new behavior in 8.4 * introducing a new argument which is already deprecated is just weird * forcing users to migrate twice (set argument in 8.4 and remove in 9.0 or 10.0) * very long migration phase in case of removing argument in 10.0 I think it would be great in this case to have a way of triggering an upcoming behavior change message even lower prio than a deprecation message but I don't see this being possible. As far as I understand you are in favor of option 1. (considering it a bugfix) but how do you make sure this will not lead to different application behavior overlooked on upgrading? Also there is no way to opt-in new behavior. Best regards Tim Düsterhus Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Tim, On 29.09.23 17:28, Tim Düsterhus wrote: Hi On 9/26/23 12:39, Marc Bennewitz wrote: I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding I find the proposal reasonable, but I don't like the deprecation proposal, because it does not allow me to opt into the *new* behavior before PHP 9.0 arrives. Getting rid of the deprecation would also require me to either add a cast everywhere or add the error suppression operator everywhere and then revert that with PHP 9 depending on whether I want the new behavior or not. As far as I can tell all the other deprecations allow me to use the replacement functionality right away without needing to go through a two-step process. As the results of not casting to float first are arguably more correct, perhaps this could be considered a bugfix. While it would cause breakage for users that rely on strict types, obtaining the old behavior is just one `(float)` cast away. The deprecation would act as an information for upcoming behavior change, not classical deprecation of future removal. If the new behavior is what you want, than you don't need to change anything as a deprecation message should not break anything. At the same time people relying on the old behavior of implicit cast gets informed that they have to cast explicit now. I first was playing around with adding a new argument. First by default keep existing behavior, in next changing default to new behavior and later again get rid of the argument. But this would force users to migrate multiple times and it would take years to finish. Changing the behavior without further notice (deprecation) this could be a huge BC ending up in a lot of uncaught bugs especially on such high frequently used functions. Best regards Tim Düsterhus Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
Re: [PHP-DEV] Re: [RFC] [Discussion] DOM HTML5 parsing and serialization support
Hi Niels, On 29.09.23 09:07, Niels Dossche wrote: Hi internals Discussion seems to have died down. Today, it's been 14 days since the last major change was done to the RFC (i.e. the class hierarchy update). And it's also been close to 4 weeks since I first announced the RFC it on the mailing list. I'd like to start the vote on Monday (20:00 PM GMT+2) and I intend to let it run for 2 weeks. Any final complaints should be raised now. Not much to complain but a question - not sure if it was discussed before. Naming: `XMLDocument::fromEmpty` vs. `HTMLDocument::createEmpty` in the PHP code section. For both, `XMLDocument::fromEmpty` and `HTMLDocument::createEmpty` there is an argument available to define the encoding but none of the other `createFrom*` methods have this argument. As far as I understand, in the these other cases the encoding gets detected from the content of the passed source but what happens is the source does not contain any information about the encoding?. E.g. you load an XML/HTML document over HTTP, the encoding is defined via HTTP header but the content itself doesn't contain it. Kind regards Niels Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Saki, On 27.09.23 02:18, Saki Takamachi wrote: Hi, Marc. There is one additional case to consider. It's backwards compatible. If `strict_types` is not `1`, the code currently out there may be passing `int` to these functions. Therefore, it is better to be aware that such code can have destructive effects, and to consider whether or not to allow it. I'm not sure I understand. All of these functions already take an `int|float` and therefore the setting of `strict_types` is irrelevant here on passing float vs. int. Regards. Saki OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi Larry, On 26.09.23 20:41, Larry Garfield wrote: On Tue, Sep 26, 2023, at 10:39 AM, Marc Bennewitz wrote: Hi internals I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding Best, Marc I'm honestly kind of confused by this. The basic concept, as I understand it, is sound. But the rest of the description seems to suggest that the returned type will depend on the passed-in type? That makes little sense to me. Since we already know that int is contravariant to float, I would expect round to return int if it can, float if there is a decimal precision set. ceil and floor should always return ints, unconditionally, because that's literally what their purpose is. But that RFC doesn't say that, which makes me quite confused. Similarly, the BC shim would therefore be (float)ceil($x), not ceil((float)$x), which... I don't think that would even do anything, would it? Currently, all three functions return float, no matter what. This is an implicit cast and results in inaccurate values for numbers above 2^53. The RFC proposes to keep the given type if possible. Given that, the return value is (and was) guaranteed to be float if the given number is float. If the given number is int the return value will most likely be int except in case of integer over- / underflow. If instead all integers would be returned as int-type, we would have additional issues... * additional BC due to additional implicit cast from float to int * less accuracy on 32bit platforms (numbers > 2^31) * what to do on integer overflow? --Larry Garfield Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
[PHP-DEV] [RFC] [Discussion] Rounding Integers as int
Hi internals I'd like to put a new RFC under discussion: https://wiki.php.net/rfc/integer-rounding Best, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
[PHP-DEV] number_format() Support rounding negative places
Hi internals, I have opened a very small PR at https://github.com/php/php-src/pull/11487 I was told to send an email here and ask for feedback. This PR adds support for rounding negative |$decimals| in |number_format()|. Previously negative |$decimals| got silently ignored and the number got rounded to zero decimal places. With this change, when |$decimals| is negative, |$num| is rounded to |$decimals| significant digits before the decimal point. This is matching the behavior for the |$precision| argument of |round()|. The previous behavior wasn't documented or tested at all. if there are no objections, Ilija has agreed to merge this for master. We will of course document this accordingly. Thanks, Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
Re: [PHP-DEV] rounding integers
On 21.05.23 17:20, Larry Garfield wrote: On Sun, May 21, 2023, at 7:18 AM, Rowan Tommins wrote: On 21 May 2023 13:00:30 BST, Dan Ackroyd wrote: On Sun, 21 May 2023 at 06:16, Marc wrote: Do you think this could be an acceptable BC-break No. Suggesting changing a 30 year old maths operations is a huge BC break. or should this be a different function? Just make your own that does precisely what you want... I agree on the first point, but disagree on the second. It's far too late to change round() itself, but the lack of built-in functions for converting to int in a controlled way is frustrating, particularly as the fashion moves towards stronger typing in general. On the surface, it sounds like a trivial operation, but there's a lot of edge cases to think about (limits of FP precision, negatives including negative zero, etc), and shipping a robust implementation of int_round, int_floor and int_ceil in core would save everyone having to rediscover them the hard way. Having recently been bitten by floor() returning a float even though the value that comes back is logically an int, I would be fully in support of "and returns an int" versions of these functions in core. Yes, ceil and floor have the same issue and probably some others as well. I remember number_format expecting float only. About changing the behavior of such an old method I also have mixed feelings about. On the one hand handling a number afterwards still wouldn't change but with more and more type safety it's probably breaking more then expected. A possible way could be to trigger some kind of warning if round/floor/ceil gets called with an integer but I don't see a good fit here as it's not a deprecation and notice/warning also does not make sense here I think. New function(s) on the other hand sounds like an ugly solution as well only helping people explicitly searching for it after they got bitten at least once. Scalar object methods, yes that would help in faaar future (only once until first release). Just thinking out loud. Marc OpenPGP_0x3936ABF753BC88CE.asc Description: OpenPGP public key OpenPGP_signature Description: OpenPGP digital signature
Re: [PHP-DEV] [RFC][Under discussion] Fetch properties in const expressions
On 24.06.22 23:55, Larry Garfield wrote: On Fri, Jun 24, 2022, at 11:43 AM, Nicolas Grekas wrote: Hi everyone I'd like to start a discussion on a simple RFC to allow fetching properties in constant expressions. https://wiki.php.net/rfc/fetch_property_in_const_expressions The RFC proposes adding support for fetching properties in constant expressions using the -> operator. I'm looking forward to your feedback. Regards, Ilija The enum-in-attribute use case came up recently in Symfony. I'm in favor and the RFC looks good to me. Genuine question: In the thread about auto-implementing Stringable for string backed enums, there is extensive argumentation to explain why ppl that use enums this way are wrong. You mentioned writing a blog post about these reasons Larry, and Benjamin (/cc) also expressed a similar opinion. So my question is: don't these arguments apply here also? Shouldn't we reject this RFC and tell ppl to use consts instead? If not, why? Nicolas A fair question. :-) (Also, I'm working on said blog post literally as we speak.) I'd say for many of the cases where the inability to use ->value has come up (eg, Attributes), a constant would indeed be the better solution. That's what people should probably be doing there. However, while there are clear downsides to letting enums auto-coerce to strings (as discussed elsewhere), I don't really see a downside to this RFC. An enum case's value or name properties are guaranteed constant and readonly, so there's no reason I can see to *not* allow them to be used in a constant, readonly context. That it would allow someone to use SomeEnum::Beep->value in a place where it would probably be better to use SomeConst::Beep instead is a mostly-harmless side effect that doesn't violate any type expectations. And, if anything, the slight clunkiness of the syntax serves as an indicator that maybe you are doing it wrong and should be looking at something else. So this patch is, in my mind, more about fleshing out a gap that fell through the cracks last version that happens to have a side effect of making connecting enums to pre-enum code possible, if a bit clunky. Auto-converting enums to other types is violating the domain model of different types and confusing their type spaces in semi-magical ways. (Also, this is an understanding of the problem space I came to just in this past week, and hadn't fully chewed through when this RFC was first put forward.) Last week I run into this limitation - just sharing in case you would see it a legitimate use case - not to say it can be done in another way: I have defined classes for some public identifiers like `UserId`. These identifiers should be prefixed which I have defined as constant. Now as I have a lot of such classes and I want to make sure all of the prefixes are unique so I added an enum with all prefixes and use the enum value as constant value as well. enum IdPrefix:string { case USER_ID = 'u-'; // ... } class UserId extends AbstractPrefixedUid { public const PREFIX = IdPrefix::USER_ID->value; } Greetings, Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] [Under Discussion] PDO driver specific sub-classes
On 21.06.22 01:01, Dan Ackroyd wrote: Hi, Following previous discussions, here is an RFC to have DB specific classes for PDO. https://wiki.php.net/rfc/pdo_driver_specific_subclasses Hi Dan, Thanks for your RFC! I do have some recommendations for it: 1. It would be great if driver specific constants would be added to the driver specific sub-classes without the driver name repeated in the const name. The counterparts living directly on PDO could be deprecated (later). PDO::SQLITE_DETERMINISTIC (int) |*> *|*|PDO::MYSQL_ATTR_USE_BUFFERED_QUERY |*(int|*)*| etc. 2. Another annoying PDO feature is the configurable behavior of exceptions. As now exceptions are the default way it would be nice to not all disabling exceptions if instantiated the new way. > Create all DB sub-classes? yes please > PQescapeIdentifier I think these should be a general PDO method but as we already have `quote` it would be preferable to name it `quoteIdentifier` or how would you explain the difference between `quote` and `escapeIdentifier`? Thanks Marc cheers Dan Ack
Re: [PHP-DEV] Alias stdClass to DynamicObject?
On 06.09.21 17:28, Nikita Popov wrote: Hi internals, In the thread for deprecation of dynamic properties, Rowan suggested that we alias "stdClass" to "DynamicObject" in https://externals.io/message/115800#115802. I wanted to split this discussion off into a separate thread, as this can be decided independently. The rationale for this is that "stdClass" is something of a misnomer: The name makes it sound like this is a common base class, as used in a number of other languages. However, PHP does not have a common base class. The only way in which "stdClass" is "standard" is that it is the return type of casting an array to (object). The actual role of stdClass is to serve as a container for dynamic properties, thus the suggested DynamicObject name. What do people think about adding such an alias? Is this worthwhile? I do like the idea very much as "stdClass" is most confusion and also wrong. The name "DynamicObject" is much better but I'm not sure if this is a good name either. * It's a class -> Why do we suffix it with "Object"? * Yes it's about dynamic properties - but is this the user goal to have dynamic properties or is it an implementation detail to get something else (map/dict)? Wouldn't it be better to name it for what purpose it's being used (map/dict/ordered dict/...) instead of how this is done? And if we want to go that route we could also add common functionalities to it like getting list of keys/values converting to array iterating etc. it's already possible right know by casting to array but it would be more logically. Yes we have assoc arrays in PHP to serve the purpose but this also has it's downsides as there is no type for it and the issue of converting an empty array from/to JSON (is it a list or a map?). The big difference, of course, is the by-ref vs. by-value. Hope that's not stupid questions? Greetings, Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php
Re: Fwd: Re[2]: [PHP-DEV] PHP 8.1 enum const expressions problem
On 30.07.21 02:01, Кирилл Несмеянов wrote: Yes, I saw this short description in your RFC ( https://wiki.php.net/rfc/enumerations ) about «enum sets». However, I do not quite understand why we can not now add a cast to scalars (string and int) and math expressions, which would solve this problem? This behavior has already been implemented for GMP objects. $mask = gmp_init(0b0001) | gmp_init(0b0010); // object(GMP) { num = 3; } echo $mask; // 3 $mask = $mask + 1; // object(GMP) { num = 4; } $mask instanceof \GMP; // true I mean, for such cases, we can create a new "virtual enum case" containing a new value instead special «EnumSetCase». enum Some: int { case A = 0b0001; case B = 0b0010; } var_dump(Some::A | Some::B); // enum(Some::@anonymous) { value = 3; } I don’t think that it is necessary to consider the «enum sets» as a separate case, cause addition is also a fairly popular case: case LAST = self::B + 1; Like any other mathematical operations. I think you missing something Consider this example: enum Some: int { case A = 0b0001; case B = 0b0010; case C = 0b0011; } var_dump(Some::B | Some::C) This should result in a set of B|C but with your logic it's the same as just C. and it also needs to work with strings: enum Some: string { case A = 'a'; case B = 'b'; case C = 'c'; } This is where enum sets comes into play. Without having PHP internals C knowledge I think it should be possible to introduce an EnumSet which internally handles a bit array where each bit is pointing to the position (ordinal) of an enum case but I don't think the ordinal position is guarantied to be stable over processes/versions so this would not directly by serializable nor do we have generics to define an enum set of a specific type (ala EnumSet). Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php
Re: [PHP-DEV] Re: [RFC] is_literal
On 18.06.21 08:00, Craig Francis wrote: On Wed, 16 Jun 2021 at 18:24, Craig Francis wrote: On Sat, 12 Jun 2021 at 18:00, Craig Francis wrote: I'd like to start the discussion on the is_literal() RFC: https://wiki.php.net/rfc/is_literal Following up on the is_literal() RFC, thanks for the feedback. It looks like there are only 2 minor open issues - updating the implementation to allow integers, and what to call the flag/function. As there’s been no issues raised with supporting integers, and doing so will help adoption, the implementation will be updated to allow them. Not sure but what happens if you have like a DB connection in big5, sjis, ... and add an integer as ASCII char into it? But that's the only edge case I can think of. Now to choose the name, with the options is_known() from Joe and is_trusted() from Moritz: https://strawpoll.com/bd2qed2xs Keep in mind it might also become a dedicated type in the future. Craig -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php
Re: [PHP-DEV] Re: [RFC] Object-scope RNG implementation
Am 19.01.21, 17:20 schrieb "Nikita Popov" : * 64-bit: I looked over your implementation, and I think your approach to handling 64-bits is correct. You only call next64() if the requested range is larger than 32-bit, and that can only happen on 64-bit systems, thus guaranteeing consistency of results (where they can be consistent at all). What I'm unsure about is the way this gets exposed to userland via next() and next64() methods. I think fetching of 64-bit values is mainly interesting as an internal optimization, and not so much important to be part of the RNGInterface API. The user is intended to get numbers via rng_rand(), not by directly calling next(). A possibility here would be to drop the RNG64Interface and next64() method, have next() always return 32-bit, but retain the internal next64 API. For this to make sense, we'd need two subsequent internal next() calls to return the same data as a single next64() call (i.e. store the result and first return one half then the other). Would this make sense to you? Wouldn't it make more sense to provide different classes for the algorithm instead of two next/64 methods or limiting it? Like: * class MT19937(system depending) * class MT19937_32 (32bit version) * class MT19937_64 (64bit version - not available on 32bit) This way the user can take the algorithm that matches best his requirements. Marc Regards, Nikita -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Enumerations
Am 05.12.20, 16:21 schrieb "Rowan Tommins" : (Apologies if this posts twice, I may have accidentally hit send before I'd finished writing it) On 05/12/2020 14:21, Marc Bennewitz wrote: > * Do cases have a stable ordinal number / position and is that accessible? >This would be very interesting on implementing an optimized EnumSet using bit-array / bit-set internally If you want to associate a stable value with each case, you can use a "primitive-equivalent enum" and assign each case an integer manually. As the RFC says: > There are no auto-generated primitive equivalents (e.g., sequential integers). I think that's a good design decision, because the language itself can't actually guarantee a stable ordinal number if the enum's author makes changes; e.g. given: enum Colour { case RED; case GREEN; case BLUE; } somebody might decide the cases should be in alphabetical order: enum Colour { case BLUE; case GREEN; case RED; } It seems unnecessarily confusing to have this be a breaking change because code somewhere relied on the ordering. It's much clearer if the author has to declare an intentional value, and can then maintain it when making cosmetic changes to their own code: enum Colour { case BLUE=3; case GREEN=2; case RED=1; } Sorry for the confusion - I mean stable within the same process - not over different processes / systems. > * I often use metadata in enumerations and so I would be very > interested to allow constants. Could you give an example what you mean? Metadata on individual cases is supported by methods, which map more cleanly to things like interfaces, and the notion of each case as a singleton object, not a static class. That said, I have a related question: can enum cases be used as the *value* of constants? e.g.: class OldMaid { public const SUIT = Suit::Spades; public const VALUE = CardValue::Queen; } If so, this leads to an interesting use case for constants on the enum itself (not the cases) to define aliases: enum Suit { case Hearts; case Diamonds; case Clubs; case Spades; const Tiles = self::Diamonds; const Clovers = self::Clubs; const Pikes = self::Spades; } // The constants and cases can be used interchangeably, since constants and cases are de-referenced with the same syntax assert(Suit::Spades === Suit::Pikes); I mean on mapping something to something else defined as a single assoc array constant. Something like: enum Role { case User, case Admin, ... } enum Action { case Order_Edit, case Order_Read, private const BY_ROLE = [ Role::User => [self::Order_Read], Role::Admin => [self::Order_Read, self::Order_Edit], ]; public function isAllowed(User $user) { return in_array($this, self::BY_ROLE[$user->role]); } } Regards, -- Rowan Tommins (né Collins) [IMSoP] -- 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
Re: [PHP-DEV] [RFC] Enumerations
Am 05.12.20, 16:08 schrieb "Larry Garfield" : On Sat, Dec 5, 2020, at 8:21 AM, Marc Bennewitz wrote: > > * How can you access a defined case value? > Something like `Suit::Spades->value()` At the moment it's only accessible via the ::cases() method. It may be appropriate to yoink the ->value() or ->value name to access it another way. We're debating that right now. The primitive equivalent case is tricky, because other languages have about 14 different ways to think about it, all of them in the end incompatible. :-) We know we don't want to just have "fancy constants," but for those cases you do want/need a primitive instead (mainly writing to a DB or screen) it needs to be easy enough to get that. There's a number of competing priorities we're trying to balance here to make the DX as clean as possible. For me it doesn't really matter how to get the primitive value as long as there is a simple way to do so. As you wrote > Passing a Primitive Case to a primitive-typed parameter or return will > produce the primitive value in weak-typing mode, and produce a TypeError in > strict-typing mode. This would already break simple function calls like the following on strlen enum Suit: string { case Hearts = 'H'; ... public function label(): string { return 'Label of ' . $this . ' with length ' . strlen($this); } // or more clear in my opinion public function label(): string { return 'Label of ' . $this->value . ' with length ' . strlen($this->value); } } To also respond to Pierre here, at present the primitives must be unique. We want to minimize the boilerplate that people have to write on every enum for common cases, and the cases() method is part of that. It won't capture everything, obviously, but if the common cases can be made trivial and the rare cases possible, that's a win. I agree here that the defined primitives needs to be unique as well. > * Do cases have a stable ordinal number / position and is that > accessible? > This would be very interesting on implementing an optimized EnumSet > using bit-array / bit-set internally The order returned from cases() is stable as lexical order, but there's no ordinal number to access. If you want a bit set, you could do: enum Permissions: int { case Read = 0x1, case Write = 0x10, case Exec = 0x100, } Right now there's no support for case ReadWrite = self::Read | self::Write. I don't know if that would be easy to add in the future, but I'd be OK with it if so. Mainly this runs into the same tricky questions around primitive equivalent handling (and what we can coax the lexer to do). > * Is it possible to detect / type-hint if something is any enum? > ` Suit::Spades instanceof Enum` > > This basically means that all enumerations would to based on a > general enum. > This would be very helpful on providing functionalities especially > for enumerations thinking about a doctrine enumeration type or again an > EnumSet / EnumMap. Not at the moment. We're discussing the implications of adding that. What exactly are EnumSet and EnumMap, in your mind? An EnumSet is a set (unique cases) of the same enumeration type. An EnumMap maps cases of the same enumeration type to another value. The interesting part here is that this can be done in a very efficient way without the need to iterate over it. Like you have defined an enumeration of 200 countries enum Country: string { case USA = 'US', case Germany = 'DE', case Australia = 'AU', ... } $set1 = Country::USA | Country::Germany; // EnumSet of [Country::USA, Country::Germany] $set2 = Country::USA | Country:: Australia; // EnumSet of [Country::USA, Country::Australia] $set3 = $set1 & $set2; // EnumSet of [Country::USA] $set4 = $set1 & ~$set2; // EnumSet of [Country:: Germany] This could of course also be done without operator overloading but it looks very clean with them __ All done internally using bit operations __ Greetings Marc --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
Re: [PHP-DEV] [RFC] Enumerations
Am 05.12.20, 00:25 schrieb "Larry Garfield" : Greetings, denizens of Internals! Ilija Tovilo and I have been working for the last few months on adding support for enumerations and algebraic data types to PHP. This is a not-small task, so we've broken it up into several stages. The first stage, unit enumerations, are just about ready for public review and discussion. The overarching plan (for context, NOT the thing to comment on right now) is here: https://wiki.php.net/rfc/adts The first step, for unit enumerations, is here: https://wiki.php.net/rfc/enumerations There's still a few bits we're sorting out and the implementation is mostly done, but not 100% complete. Still, it's far enough along to start a discussion on and get broader feedback on the outstanding nits. I should note that while the design has been collaborative, credit for the implementation goes entirely to Ilija. Blame for any typos in the RFC itself go entirely to me. *dons flame-retardant suit* Hi Larry, thanks for your great initiative and hard work in this! I'm the author of an emulated enumeration lib [1] and really looking forward seeing native enumeration support in PHP. Here are some questions about your RFC: * How can you access a defined case value? Something like `Suit::Spades->value()` * Are the cases case-insensitive or case-sensitive? `Suit::Spades` vs. `Suit::SPADES` * Are cases serializable? `Suit::Spades === unserialize(serialize(Suit::Spades)) // true` * Do cases have a stable ordinal number / position and is that accessible? This would be very interesting on implementing an optimized EnumSet using bit-array / bit-set internally * I often use metadata in enumerations and so I would be very interested to allow constants. I do understand that they share the same naming table and these needs to be unique but disabling constants altogether would limit the use-cases in my opinion. * Is it possible to detect / type-hint if something is any enum? ` Suit::Spades instanceof Enum` This basically means that all enumerations would to based on a general enum. This would be very helpful on providing functionalities especially for enumerations thinking about a doctrine enumeration type or again an EnumSet / EnumMap. Thanks Marc [1] https://github.com/marc-mabe/php-enum -- Larry Garfield la...@garfieldtech.com -- 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
Re: [PHP-DEV] [RFC][Under Discussion] Add functions array_key_first()and array_key_last()
Hi all, I just want to add some information that I feel it's missing in that discussion - I'm sorry if it was mentioned already. 1. It's already possible to extract the key and value of any index position of an array using array_slice: https://3v4l.org/mib99 2. "array_[key|value]_[first|last]($array)" is in my opinion not a good option as it lacks the possibility to extract key/value from any position. Something like "array_[key|value]_index($array, $index)" where $index would be the index position or negative index position from right. Thanks, Marc Am 21.06.2018 um 18:16 schrieb Larry Garfield: On Tuesday, June 19, 2018 9:47:01 PM CDT Levi Morrison wrote: I don't think I'm getting all the mail I am supposed to. I hope this gets seen. I propose 2 functions *only* which I believe covers the use-cases that all 4 of these do and more, with shorter names, and the ability to discern whether the call succeeded or not. list($key, $value) = array_first($input); // $key will be null if the call failed list($key, $value) = array_last($input); // $key will be null if the call failed I have tested it with user-land functions and seems to work as intended in all success and failure conditions. Verification that it works as intended with internal functions is necessary but this seems a much better proposal to me. Can I vote "heck no" to any function that does multi-return, thus making it impossible to chain or pass directly to another function? That's an idiom that just doesn't make sense in PHP. --Larry Garfield -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] PHP_OS_FAMILY and macOS
Am 13.06.2017 um 21:35 schrieb Davey Shafik: Given that iPad (and iPhone) both run iOS which is based on Darwin, and Apple just relaxed the rules on running interpreted code, and we are already seeing IDEs spring up for the device, we should use "Darwin", rather than "Mac". This also encompasses other distros like PureDarwin. nice catch +1 from me - Davey On Tue, Jun 13, 2017 at 6:47 AM, Sebastian Bergmannwrote: Am 13.06.2017 um 15:00 schrieb Zeev Suraski: Yep, Mac sounds like a fairly future-proof choice, and is also consistent with the capitalization of other options. Implemented in http://git.php.net/?p=php-src.git;a=commitdiff;h= 362d2e42a02fe018a7d1261a53ff59b73fed91f6 -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [PATCH] Make var_export() output "(object)array(..." instead of "stdClass::__set_state(..." for stdClass
Am 14.03.2017 um 20:26 schrieb Fleshgrinder: On 3/14/2017 7:57 PM, Andrea Faulds wrote: Hi everyone, Since stdClass has no __set_state method, var_export() produces unusable output if given an object of that class. I wrote a patch that would make var_export() produce a cast to object instead, which could be evaluated to get back a stdClass: https://github.com/php/php-src/pull/2420 Any thoughts/comments? If you're wondering about whether a __set_state method should be added to stdClass, I posted some thoughts in the pull request discussion already. Thanks! I actually already used __set_state occasionally for userland classes. Adding __set_state to stdClass seems to be more consistent with the rest of PHP, rather than special casing it in one method. I cannot see any issues with this to be honest. Personally I would like to have a more reasonable way in general. No special case and no magic method. So my proposal then would be to try to add a class cast operator (needs an own RFC) and later to with this approach on var_export. Example: class Foo {} $std = new stdClass; $foo = new Foo; $arr = ['arr' => 'arr']; var_dump((object)$std); // no change var_dump((array)$std);// no change var_dump((Foo)$std); // object of class Foo var_dump((object)$foo); // no change var_dump((stdClass)$foo); // object of class stdClass var_dump((array)$foo);// no change var_dump((array)$arr);// no change var_dump((object)$arr); // no change var_dump((stdClass)$arr); // object of class stdClass var_dump((Foo)$arr); // object of class Foo Thoughts? Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Re: [RFC][Discuss] Arrow Functions
Am 31.01.2017 um 05:53 schrieb Stephen Reay: Hi Andrea, All, On 31 Jan 2017, at 08:12, Andrea Fauldswrote: Is it necessary to introduce a new keyword, fn? I think you'd get a similar benefit from: function($x) => $arr[$x] Likewise, is it necessary to restrict auto-capture to the => syntax? Couldn't we allow the following? function ($x) { return $arr[$x]; } I agree that the `fn` keyword isn’t really necessary. I’ve never quite understood how arrow functions with implied returns etc are supposed to make for *more* readable code, but if they’re going to be part of the language please at least keep some consistency with regular closures. In the case that regular closures got auto-capture, would a `use($foo, $bar, $baz)` segment on a closure still be honoured (i.e. disable auto-capture), and would it have any impact (positive or negative) on performance/memory usage? After several years of JS closure ‘fun’ I kind of like that with PHP you only inherit the variables you explicitly `use()` in closures. I like the general idea, too. But with similar feelings for: - Introducing a second keyword for closures is confusing - and mor confusing if they are basically the same words - Also I like the "use" keyword you have to define your variables -> Would it be helpful to allow "function () use (*) {}" to inline all available variables? - Or based on Rowans idea to stretching the brackets but using the function keyword: function($x => $arr[$x]) Thanks Marc Cheers Stephen -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] Allow "static" type
Hi all, I would like to know your opinion about using "static" as type-hint similar to "self" and how simple / complex it would be to implement. Example - using static: https://3v4l.org/XqDma class Base { public static function test(static $obj) : static { echo get_class($obj) . "\n"; return new static($obj); } } class Ext extends Base {} $base = new Base; $ext = new Ext; Base::test($base); Base::test($ext); Ext::test($ext); Ext::test($base); Example - using self: https://3v4l.org/Tp7k6 - Boilerplate code to check if the given argument is an instance of static - No way for IDEs to test Ext::test returning an instance of Ext class Base { public static function test(self $obj) : self { echo get_class($obj) . "\n"; if (!$obj instanceof static) { throw new InvalidArgumentException(sprintf( "Object (%s) must be an instance of %s", get_class($obj), static::class )); } return new static($obj); } } class Ext extends Base {} $base = new Base; $ext = new Ext; Base::test($base); Base::test($ext); Ext::test($ext); Ext::test($base); Thanks Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC][DISCUSSION] Object type hint, now with added variance
Am 23.11.2016 um 01:52 schrieb Dan Ackroyd: Hi, This is the reintroduction of the Object Type RFC for discussion. There was previously strong feedback from people who would prefer that the inheritance checks for methods that use object types should be co/contravariant. This has been added to the RFC. https://wiki.php.net/rfc/object-typehint I like this RFC :) And I have a question where I'm not sure if that should be catched by this RFC, too: If I declare a return type of "object" and extends that to return "static" it doesn't compile because "static" is not a valid return type yet. https://3v4l.org/lp3AB/rfc#version=rfc-typed-properties class Test { public static function factory() : object { return new static(); } } class Test2 extends Test { public static function factory() : static { return parent::factory(); } } cheers Dan Ack -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] strtod and NaN vs. zero
Hi Andrea, Am 24.10.2016 um 15:40 schrieb Andrea Faulds: Hi, Marc Bennewitz wrote: But I'm still curious why casting any non numeric string results in the valid number float(0) where there is a special value in floating point numbers declared to represent not a number values. Because that's what C's strtod() does, and it's also what (int) does (because that's what C's strtol()) does. There'd be an argument for using NaN, sure, but it wouldn't be consistent with the rest of the language. Generally, PHP assumes that a string with no leading digits has the number value of zero. This is true not only in (int) and (float) casts, but also in generic number coercion operations, like with +, -, *, / and **. To change the behaviour of (float) here would be to introduce a new inconsistency to PHP. If we go for NaN everywhere, then we introduce a different problem: (int) should return an integer, and the generic number coercions prefer giving you an integer rather than a float if appropriate. Producing a NaN here would mean you'd now get an int rather than a float, and would cause a cascading change in operation result types which could lead to previously working code now throwing lots of E_WARNINGs or TypeErrors (NaN is not accepted for integer type declarations in weak mode, and all floats are not accepted for integer type declarations in strict mode). Thanks for your explanation. It's totally true that on casting non numeric string to integer will result in 0 but that's a different type even if it's also a numeric type. From my understanding PHP tries to cast from one type to another by loosing as less information as possible. In this case I see a non numeric string that gets casted to a float will loose exactly this information that it's "Not a Number" where it would be possible to keep this information. On casting this to int there is of course no possibility to keep it but I don't see where it's inconsistent as it's a different type used for different use-cases. Having mathematical operations with non numeric strings should result in the same behavior as NaN will result in NaN which makes sense and I don't see where it will throw lots on WARNINGS or TypeErrors as it's still a float. Since PHP-7.0 there was a WARNING introduced "A non-numeric value encountered" which is nice but the result is still a valid float where "Not a Number" would be more logical. That's of course my personal opinion. Of course changing this would introduce a BC break and therefore should be reviewed safely. But the bug #73329 shows that there is not much attention as it stayed for some versions. This mail is not an RFC not even a proposal it's just mail to get an answered why (Thanks again) and to see how others think about. Thanks. Thanks Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] strtod and NaN vs. zero
Am 23.10.2016 um 21:13 schrieb Marc Bennewitz: Am 23.10.2016 um 13:49 schrieb Niklas Keller: 2016-10-23 12:55 GMT+02:00 Marc Bennewitz <dev@mabe.berlin <mailto:dev@mabe.berlin>>: Hi internals, On casting a non numeric value to a float in PHP the result will be float(0). In PHP-7.0 an exception was introduced that on casting a string "/\s*NaN\s*/i" will result in float(NaN). https://3v4l.org/2Xakm Wouldn't it be more logical and expected to return NaN in all cases of casting a non numeric string to a floating point number? Thanks Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php +1 I just noticed that the behavior change in PHP-7 has been "fixed" already by https://bugs.php.net/bug.php?id=73329. So the old behavior will be presented soon. But I'm still curious why casting any non numeric string results in the valid number float(0) where there is a special value in floating point numbers declared to represent not a number values. I also did a small research on other languages and found the following: C strtod returns float(0) -> but supports converting the strings "INFINITY" or "NAN" (case-insensitive) JavaScript returns NaN I forgot to mention that in JavaScript (parseFloat) it is nearly the behavior I would expect. The only difference is that it allows the string +/- "Infinity" to be casted to Infinity. Python throws ValueError: could not convert string to float -> but supports the string +/- "NaN", "Inf", "Infinity" (case-insensitive) Perl returns float(0) -> but supports the string +/- "NaN", "Inf", "Infinity" (case-insensitive) So there is a nice mix of how other languages will handle this problem. In my opinion it still makes much more sense to return NaN in any case a not numeric string will be casted to float incl. "Inf" and "Infinity". (If spaces should be ignored or suffixes allowed is another question) = The beginning of a string must contain at least one number by ignoring spaces to be casted to a valid floating point number. In any other situations NaN must be returned because this represents what it is = Not a Number. So for me the following example table makes sense: In -> Out "" -> NaN " " -> NaN "+" -> NaN "-" -> NaN "." -> NaN ".5" -> 0.5 "0.5" -> 0.5 " 0.5" -> 0.5 "0" -> 0 " 0" -> 0 "Nan" -> NaN "Inf" -> NaN "Info" -> NaN "foo" -> NaN ".foo" -> NaN ".2foo" -> 0.2 " .2foo" -> 0.2 "foo1" -> NaN "foo." -> NaN "foo0.1" -> NaN Thoughts Marc Regards, Niklas -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] strtod and NaN vs. zero
Am 23.10.2016 um 13:49 schrieb Niklas Keller: 2016-10-23 12:55 GMT+02:00 Marc Bennewitz <dev@mabe.berlin <mailto:dev@mabe.berlin>>: Hi internals, On casting a non numeric value to a float in PHP the result will be float(0). In PHP-7.0 an exception was introduced that on casting a string "/\s*NaN\s*/i" will result in float(NaN). https://3v4l.org/2Xakm Wouldn't it be more logical and expected to return NaN in all cases of casting a non numeric string to a floating point number? Thanks Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php +1 I just noticed that the behavior change in PHP-7 has been "fixed" already by https://bugs.php.net/bug.php?id=73329. So the old behavior will be presented soon. But I'm still curious why casting any non numeric string results in the valid number float(0) where there is a special value in floating point numbers declared to represent not a number values. I also did a small research on other languages and found the following: C strtod returns float(0) -> but supports converting the strings "INFINITY" or "NAN" (case-insensitive) JavaScript returns NaN Python throws ValueError: could not convert string to float -> but supports the string +/- "NaN", "Inf", "Infinity" (case-insensitive) Perl returns float(0) -> but supports the string +/- "NaN", "Inf", "Infinity" (case-insensitive) So there is a nice mix of how other languages will handle this problem. In my opinion it still makes much more sense to return NaN in any case a not numeric string will be casted to float incl. "Inf" and "Infinity". (If spaces should be ignored or suffixes allowed is another question) = The beginning of a string must contain at least one number by ignoring spaces to be casted to a valid floating point number. In any other situations NaN must be returned because this represents what it is = Not a Number. So for me the following example table makes sense: In -> Out "" -> NaN " " -> NaN "+" -> NaN "-" -> NaN "." -> NaN ".5" -> 0.5 "0.5" -> 0.5 " 0.5" -> 0.5 "0" -> 0 " 0" -> 0 "Nan" -> NaN "Inf" -> NaN "Info" -> NaN "foo" -> NaN ".foo" -> NaN ".2foo" -> 0.2 " .2foo" -> 0.2 "foo1" -> NaN "foo." -> NaN "foo0.1" -> NaN Thoughts Marc Regards, Niklas -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] strtod and NaN vs. zero
Hi internals, On casting a non numeric value to a float in PHP the result will be float(0). In PHP-7.0 an exception was introduced that on casting a string "/\s*NaN\s*/i" will result in float(NaN). https://3v4l.org/2Xakm Wouldn't it be more logical and expected to return NaN in all cases of casting a non numeric string to a floating point number? Thanks Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] Class Constant Visibility BC Break
Hi, I encountered a problem of my library with the new class constant visibility functionality. The problem is that I'm using ReflectionClass::getConstants() to detect class constants but I'm only interested in public constants. Before class constants were public by definition but now it can be private and protected, too. I know the new methods ReflectionClass::getReflectionConstant[s]() are available to detect exactly what I need and that's fine! But of course using ReflectionClass::getConstants() no longer returns public class constants by default. So for me this is a BC break but it wasn't listed in the RFC. I don't know if it was discussed before but it could be avoided by adding an argument to ReflectionClass::getConstants() to filter by visibility which defaults to public. Thoughts? PS: I'm talking my library to emulate enumerations https://github.com/marc-mabe/php-enum/blob/master/src/Enum.php#L295-L327 but this BC break happens to all using ReflectionClass::getConstants() for public constants only e.g. accessing values later with constant(). Cheers Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Bug or expected behavior?
On 05/31/2016 09:59 PM, Nikita Popov wrote: On Tue, May 31, 2016 at 9:54 PM, Marc Bennewitz <dev@mabe.berlin <mailto:dev@mabe.berlin>> wrote: Hi, today I was running into an issue with a function lookup over namespace. https://3v4l.org/qF7cK fails https://3v4l.org/evVic works For me it looks like the function lookup for "is_null" in this case gets cached on first use and on second call no check will be done if this function exists in the current namespace before looking in the root namespace. Because PHP is a dynamic language this behavior looks wrong (unexpected) to me and also HHVM does handle it as I would expect it. Thanks, Marc This is a known issue: https://bugs.php.net/bug.php?id=64346 Much thanks Nikita for the link. Didn't found it myself. But this bug ticket doesn't look nice - No comments since 2¹/² years. Is a suggestion from someone without enough knowledge of the engine / opcache. Wouldn't it be better to move this performance feature into opcache and make it configurable over "opcache.optimization_level <http://php.net/manual/en/opcache.configuration.php#ini.opcache.optimization-level>"? Regards, Nikita Thanks, Marc
[PHP-DEV] Bug or expected behavior?
Hi, today I was running into an issue with a function lookup over namespace. https://3v4l.org/qF7cK fails https://3v4l.org/evVic works For me it looks like the function lookup for "is_null" in this case gets cached on first use and on second call no check will be done if this function exists in the current namespace before looking in the root namespace. Because PHP is a dynamic language this behavior looks wrong (unexpected) to me and also HHVM does handle it as I would expect it. Thanks, Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Fix inconsistent behavior of $this variable
On 05/24/2016 11:57 AM, Rowan Collins wrote: On 24/05/2016 06:45, Jesse Schalken wrote: I'm curious, what is it about $this that makes it special in the first place? Can't it be a normal local variable that happens to already be assigned at the start of a method? There are a few things that take advantage of its specialness, e.g. - binding a closure to an object changes the meaning of $this in a way very different from assigning it into scope with "use($this)" - a method declared static can detect and throw errors on anything referencing $this - when calling parent::foo() from an instance method, the value of $this needs to be set appropriately on the new method; being able to reassign $this could lead to some odd behaviour there Python's approach is certainly valid, and leads to some different useful properties, I'm sure, but it's a very different design, not just a more relaxed attitude to assignment. As of $this is a very special variable where only the engine is (or should) be allowed to change. I would like to ask you if it wouldn't be better to NOT define $this as a special variable including a lot of code to make sure this variable doesn't get re-assigned but instead define this as a keyword like self where the syntax makes sure it can't be re-assigned and it's less special and simpler to learn for beginners. I know it would be a huge BC break but for me it sounds more "right" and could also be introduced in parallel to $this for a long long time but without a lot of overplayed code for $this. Thanks, Marc Regadrds, -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Immutable modifier
FYI there was a very small discussion about it ~ 1 year ago https://www.mail-archive.com/internals@lists.php.net/msg71521.html On 11/16/2015 10:15 AM, Chris Riley wrote: Hi, There has been a lot of interest recently (eg psr-7) in immutable data. I'm considering putting an RFC together to add language support for immutables: immutable class Foo { public $bar; public function __construct($bar) { $this->bar = $bar; } } Immutable on a class declaration makes all (maybe only public?) properties of the class immutable after construct; assigning to a property would result in a Fatal error. class Foo { public $bar; immutable public $baz; } Immutable on a property makes the property immutable once it takes on a none null value. Attempts to modify the property after this results in a fatal error. Any thoughts? ~C -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [Question] Variadic method signature compatibility between 5.6 and 7.0
Hi Rowan, On 11/02/2015 05:41 PM, Rowan Collins wrote: Alexander Lisachenko wrote on 02/11/2015 11:12: First definition declares exactly one single parameter, which can be absent during the method call, so I can even write public static function test() {} Second definition defines zero or more arguments, so it can be also described by the same signature: public static function test() {} OK, I got a bit confused with the different optional parameters, and neither your explanation nor Andrea's quite did it for me. But, I think you're right that this should be compatible, if the rule is "any legal call on the parent should also be legal on the child". Currently, all versions of PHP enforce the following: - if parent accepts no parameters, child must accept zero, but could accept one or more optional parameters - if parent accepts zero or one (an optional parameter), child must accept zero, must accept one, but could accept more (so, two optional parameters is fine; no parameters at all is incompatible) Thus this is acceptable: class Foo { public function test() {} } class Bar extends Foo { public function test($foo = null) {} } But these are all not: class Foo2 { public function test($foo = null) {} } class Bar2 extends Foo2 { // Doesn't accept one parameter public function test() {} } class Baz2 extends Foo2 { // Doesn't accept zero parameters public function test($foo) {} } class Foo3 { public function test() {} } class Bar3 extends Foo3 { // Doesn't accept zero parameters public function test($foo) {} } Variadic signatures count as "zero or more" when the parent accepts only zero: class Foo4 { public function test() {} } class Bar4 extends Foo4 { public function test(...$foo) {} } But where the parent accepts "zero or one", the following ought to be compatible because calls with no parameters, and calls with one parameter, would both be valid: class Foo { public function test($foo = null) {} } class Bar extends Foo { public function test(...$foo) {} } In short, I agree with you that this warning is incorrect, but will leave this here in case anybody else is equally confused (and becomes any less so by reading this...) In my opinion the warning is valid as the one method defines one optional argument and the overwritten method would accept no or more arguments where the no arguments is wrong: https://3v4l.org/6eMiu class Foo { public function test($foo = null) {} } class Bar extends Foo { public function test() {} } The first defined argument gets more interesting if it defines a type-hint what is not possible to define as variadic: https://3v4l.org/HQdvI class Foo { public function test(Foo $foo = null) {} } class Bar extends Foo { public function test(...$bar) {} } Additionally this issue can simply be addressed by: https://3v4l.org/74r3K class Foo { public function test(Foo $foo = null) {} } class Bar extends Foo { public function test(Foo $foo = null, ...$bar) {} } Regards, Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Void Return Type (v0.2, reöpening)
On 10/15/2015 01:19 AM, Larry Garfield wrote: On 10/14/2015 06:00 PM, Andrea Faulds wrote: >> Both you and Stas have said this, but it's only true if we solely >> consider C-like languages. Other languages do different things. In >> the PHP manual, Hack, TypeScript, ActionScript, and most likely other >> languages (these are just off the top of my head), `void` functions >> do still have an implicit result. >> >> All of these languages would have had the choice to do what you're >> suggesting and use `null`, or its equivalent (`undefined` for >> TypeScript and ActionScript). They didn't. Why? If I had to guess, >> there's at least three reasons. For one, void is the word languages >> usually use for this. For another, `void` and `null` they mean >> different things. `void` signifies a function isn't returning >> anything. `null` signifies a function that *returns null*, regardless >> of where that null came from. `function foo(): null { return >> some_probably_null_returning_function(); }` should surely be legal >> with a `null` type hint, yet it's nonsensical code. Finally, making a >> function truly "return nothing", i.e. disallowing its use as an >> expression/rvalue, breaks some use cases, like passing along the >> result of a callback. >> >> PHP would neither be the first nor the last to be using `void` in >> this way. >> >>> If the union types RFC[2] passes it >>> makes sense to allow `Foo | null` which allows something of type `Foo` >>> or `null`. To me it makes sense that if you then remove `Foo` you are >>> left with `null`, not `void`. My personal recommendation because of >>> this would be to use `null` for the return type and instead of `void`. >> >> `null` would be a weird type, because it doesn't make sense as a >> parameter type, and as a return type, you don't really want to >> enforce returning null, you want to enforce not returning at all (see >> the example above). It feels like a poor man's substitute to me. >> >> Thanks. > > The tricky part here is that saying a function does not return is not > something PHP currently does: > > https://3v4l.org/HtAuC > > No return implicitly returns NULL, which you can assign to a variable > if, for some strange reason, you were so inclined. So this would be > more than "just" a syntactic documentation feature. > > Which I believe gives the following options: > > 1) Change the language behavior such that > > function foo() : void { ...} > $a = foo(); > > Is a syntax error (because there really was nothing returned to > assign), rather than resulting in $a having a value of NULL. > > 2) Use null as a "type" (which I agree feels weird just saying it), > such that: > > function foo() : null { ...} > $a = foo(); > > and > > function foo() { ...} > $a = foo(); > > are identical. The former would impact the contents of the function > (eg, a non-empty return would be a parse error), but the external > result is the same ($a == NULL). > > 3) Use the "void" keyword, but give it the same effect as option 2. > > The RFC currently seems to propose option 3 (based on the "Use of void > functions in expressions" section). I don't have a strong feeling at > this point about which option I'd prefer. > Option 4) // implicit return void function foo () { return; } // explicit return void function foo () : void { return; }; // syntax error if returning something on explicit return void function foo () : void { return null; }; // syntax error on using return value of explicit return void function foo () : void { return; }; $bar = foo(); // return NULL on implicit return void (this could also give a warning/notice/deprecated error) function foo () { return; }; $bar = foo(); // NULL // mixing return void with any other return values could also result in a warning/notice/deprecated error function foo () { if ($bar) return; return $bar; }; --Larry Garfield > I really like this as in my opinion if a function doesn't return something it should be part of the function signature and it really helps to avoid mistakes on writing code. Marc
Re: [PHP-DEV] Re: [RFC] [Concept] Class Constant visibility modifiers in PHP 7.1+
On 09/07/2015 08:43 AM, Sean DuBois wrote: On Sun, Sep 06, 2015 at 06:47:56PM +0100, Andrea Faulds wrote: Hi Sean, Sean DuBois wrote: I am starting this discussion to get peoples opinion on the overall feature, and find someone who would be interested in watching over my progress and making sure I do the right things to hopefully get this merged. The PHP bug tracker contains a few simple entries for a adding visibility modifiers to class constants. https://bugs.php.net/bug.php?id=27022 I would be the one implementing this, and have a basic working version already (that takes shortcuts like reusing property_info) but it works! https://github.com/Sean-Der/php-src/compare/master...bug-69980-class-constants#diff-6231c13c8582758f41a5e2a015e3b5c5R1 There are cases where runtime/compile time checks pass/fail incorrectly, but working on that now. This change would involve breaking the API, but wouldn't involved any language breaking changes. All current const declarations would just default to public and keep the same behavior. Funny you should propose this now, I was wanting this feature just the other day. This would be a useful addition, and clean up a strange inconsistency: why can methods and properties have visibility modifiers, but not constants? I'd love to see this in PHP. Are you going to write an RFC? Thanks! -- Andrea Faulds http://ajf.me/ Just one of those things that you you wish you had, but then end up solving with other things (static properties) so we will see how long it takes me to blunder through it :) Reeze Xia started an RFC, but didn't have time to finish it. We talked over GitHub and I will be taking it over fully. https://wiki.php.net/rfc/class_const_visibility I am just waiting on RFC Karma, after I get that I will start filling it in! I really like this feature but please make sure it doesn't break BC on usage of Reflection::getConstant(s). For example I'm using this for an implementation of constant based enumerations: (https://github.com/marc-mabe/php-enum/blob/master/src/Enum.php#L277) Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Headsup: PHP7 feature freeze
On 06/28/2015 09:22 PM, Christoph Becker wrote: Marc Bennewitz wrote: On 06/25/2015 09:48 PM, Aaron Piotrowski wrote: On Jun 25, 2015, at 2:39 PM, Marc Bennewitz dev@mabe.berlin mailto:dev@mabe.berlin wrote: Nice to see this - didn't noted it in the last month :) But there is one edge case that is not handled by PHP-7 at current behavior; http://3v4l.org/HkRQ7 class Foo { public static function __callStatic($m, $args) { var_dump($m); } public function __call($m, $args) { var_dump($m); } } $callable = [new Foo, '']; $callable(); // string(0) $callable = 'Foo::'; $callable(); // Fatal error: Uncaught Error: Call to undefined function Foo::() This behavior is inconsistent! Thanks Marc Interesting, I didn’t consider that an empty method name should invoke __callStatic(). I’ll look into fixing this sometime today or tomorrow. Is this edge case addressed now? My PR has been closed now where this edge case was addressed, too. That is supposed to be addressed by http://git.php.net/?p=php-src.git;a=commit;h=ba67fc221890aaa395912aefebb96155afe671c1. Can you please confirm with a recent master? (The Windows snapshots currently in build progress are likely to have this commit included, too.) It's fixed now - Thanks! :) -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Headsup: PHP7 feature freeze
On 06/25/2015 09:48 PM, Aaron Piotrowski wrote: On Jun 25, 2015, at 2:39 PM, Marc Bennewitz dev@mabe.berlin mailto:dev@mabe.berlin wrote: Nice to see this - didn't noted it in the last month :) But there is one edge case that is not handled by PHP-7 at current behavior; http://3v4l.org/HkRQ7 class Foo { public static function __callStatic($m, $args) { var_dump($m); } public function __call($m, $args) { var_dump($m); } } $callable = [new Foo, '']; $callable(); // string(0) $callable = 'Foo::'; $callable(); // Fatal error: Uncaught Error: Call to undefined function Foo::() This behavior is inconsistent! Thanks Marc Interesting, I didn’t consider that an empty method name should invoke __callStatic(). I’ll look into fixing this sometime today or tomorrow. Is this edge case addressed now? My PR has been closed now where this edge case was addressed, too. Thanks, Aaron Piotrowski Thanks Marc
Re: [PHP-DEV] Headsup: PHP7 feature freeze
On 06/25/2015 09:31 PM, Christoph Becker wrote: Marc Bennewitz wrote: I would really like to see directly calling a string of Class::method be fixed for 7.0. It's currently resulting in a fatal error and is inconsistent with call_user_func[_array], is_callable and the callable type-hint. There is also a PR open since April 2014 : https://github.com/php/php-src/pull/659 Apparently, your PR has been overlooked, but it seems this is already implemented as result of merging PR #1264[1]; see http://3v4l.org/W8hQA. Can you please verify, and close your PR #659 as appropriate. [1] https://github.com/php/php-src/pull/1264 Nice to see this - didn't noted it in the last month :) But there is one edge case that is not handled by PHP-7 at current behavior; http://3v4l.org/HkRQ7 class Foo { public static function __callStatic($m, $args) { var_dump($m); } public function __call($m, $args) { var_dump($m); } } $callable = [new Foo, '']; $callable(); // string(0) $callable = 'Foo::'; $callable(); // Fatal error: Uncaught Error: Call to undefined function Foo::() This behavior is inconsistent! Thanks Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Headsup: PHP7 feature freeze
On 06/25/2015 09:39 PM, Marc Bennewitz wrote: On 06/25/2015 09:31 PM, Christoph Becker wrote: Marc Bennewitz wrote: I would really like to see directly calling a string of Class::method be fixed for 7.0. It's currently resulting in a fatal error and is inconsistent with call_user_func[_array], is_callable and the callable type-hint. There is also a PR open since April 2014 : https://github.com/php/php-src/pull/659 Apparently, your PR has been overlooked, but it seems this is already implemented as result of merging PR #1264[1]; see http://3v4l.org/W8hQA. Can you please verify, and close your PR #659 as appropriate. [1] https://github.com/php/php-src/pull/1264 Nice to see this - didn't noted it in the last month :) But there is one edge case that is not handled by PHP-7 at current behavior; http://3v4l.org/HkRQ7 class Foo { public static function __callStatic($m, $args) { var_dump($m); } public function __call($m, $args) { var_dump($m); } } $callable = [new Foo, '']; $callable(); // string(0) $callable = 'Foo::'; $callable(); // Fatal error: Uncaught Error: Call to undefined function Foo::() This behavior is inconsistent! Thanks Marc It's also inconsistent with $callable = ['Foo', '']; -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Headsup: PHP7 feature freeze
On 06/25/2015 05:03 PM, Kalle Sommer Nielsen wrote: Howdy This is a quick heads up that we plan to have the next release of 7.0.0 be Beta 1, this marks a feature freeze and from there on, we will switch focus on to stabilization, regressions and other bug fixes. Beta 1 is schedule to be tagged and packaged on July 7th and released on July 9th which is a small 2 weeks from now to get any remaining changes of such in. If you are in doubt about whether or not your change would be considered a 'feature' or have any other questions, then feel free to mail us RMs or reply here. I would really like to see directly calling a string of Class::method be fixed for 7.0. It's currently resulting in a fatal error and is inconsistent with call_user_func[_array], is_callable and the callable type-hint. There is also a PR open since April 2014 : https://github.com/php/php-src/pull/659 Thanks, Kalle, Anatol Ferenc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Migrating PHP classes to built in namespace
On 06/04/2015 10:01 AM, Yasuo Ohgaki wrote: Hi all, On Thu, Jun 4, 2015 at 12:07 AM, Sara Golemon poll...@php.net wrote: On Wed, Jun 3, 2015 at 1:33 AM, Dominic Grostate codekest...@googlemail.com wrote: Has there been any discussion or consideration towards migrating or at least aliasing all built in classes to a Php vendor namespace? Not any that's led to a consensus. Personally, I like the idea of moving EVERYTHING to PHP\ at once and building in an automatic fallback, so an app could do: ?php $dt = new DateTime(...); // uses builtin DataTime via fallback to PHP namespace Or: ?php class DateTime { ... } $mydt = new DateTime(...); // Uses user supplied DateTime $pdt = new PHP\DateTime(...); // Uses builtin DateTime It's acceptable option, but I prefer explicit declaration for clean root namespace. Possibly paired with the ability to import a NS to root: ?php use PHP as \; $pdt = new DateTime(...); // Uses builtin DateTime from root namespace +1 for as \ It achieves both clean namespace and compatibility at the same time. It opens door for easier API version up also. Automatic fallback disturbs this. This one is not compatible with current code as you have to alias the PHP namespace to the root one before using full classes like \DateTime. PS: I like a lower case php much more than upper case PHP ;) Regards, -- Yasuo Ohgaki yohg...@ohgaki.net -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Method call overhead
On 06/04/2015 06:35 AM, Yasuo Ohgaki wrote: Hi Brian, On Thu, Jun 4, 2015 at 7:33 AM, Brian Moon br...@moonspot.net wrote: This is a better representation of what you are trying to show. It removes all the magic call back stuff that could be adding to the slowness you are seeing. In addition, it does not create a new object on every call for the object method. Creating a new object is going to explicitly slow things down. But, it's not related to the call time. http://3v4l.org/biM9G This version adds up precision errors because microtime() precision is not high enough for the purpose. Since the error is random, it does not affect proportion much but total execution time. Following damn code does better job for these kinds of benchmarks. http://3v4l.org/eJK07 See the total amount of execution time recorded. If we really need pure execution time, then it should record for loop execution time with empty body. - incl. displaying the time for the loop: http://3v4l.org/1vZJI Regards, -- Yasuo Ohgaki yohg...@ohgaki.net -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Throwable Interface
On 05/24/2015 10:11 PM, Aaron Piotrowski wrote: On May 24, 2015, at 2:08 PM, Marc Bennewitz dev@mabe.berlin wrote: Where are the new classes and the interface located if it's not in the global namespace or do I muss something? Sorry if what I wrote wasn’t clear. Throwable, Error, TypeError, and ParseError will be built-in interfaces/classes in the root namespaces. So users will not be able to make classes with those exact names, but classes with those names in a non-global namespace (e.g., \Vendor\Package\TypeError) will still be possible. I’ve updated the RFC to make this clearer. Thanks If I remember right the TypeException/TypeError will be thrown in some cases of internal functions with strict argument count. In my opinion a missing argument or to much arguments has nothing to do with the type and should have it's own Exception/Error class. I believe this actually generates a warning, it does not throw an exception. However, this does remind me of another point: It is possible that more classes extending Error could be created in the future for different error reasons. Anything that throws an Error could later be changed to throw an object extending Error without a BC break. This is a separate issue though and could be discussed in a future RFC. Ok than I remember wrong. Aaron Piotrowski Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Throwable Interface
On 05/24/2015 11:32 PM, Yasuo Ohgaki wrote: Hi Aaron, On Sun, May 24, 2015 at 5:12 AM, Aaron Piotrowski aa...@icicle.io wrote: I’ve created an RFC for modifying the exception hierarchy for PHP 7, adding Throwable interface and renaming the exceptions thrown from fatal errors. The RFC is now ready for discussion. RFC: https://wiki.php.net/rfc/throwable-interface https://wiki.php.net/rfc/throwable-interface Pull Request: https://github.com/php/php-src/pull/1284 https://github.com/php/php-src/pull/1284 Does this include internal function type errors? e.g. $ php -r 'var_dump(mt_srand(999));' PHP Warning: mt_srand() expects parameter 1 to be integer, string given in Command line code on line 1 NULL If not, please make these exceptions rather than E_WARNING. We need consistency here. This would be great for strict_types mode as there it results in a fatal error. http://3v4l.org/vHl8K Regards, -- Yasuo Ohgaki yohg...@ohgaki.net -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] ::class wrong case
Hi, I have noted that detecting a class name using ::class it will return the called case instead of the original case. see http://3v4l.org/97K36 That's annoying as I like to check the right class case on autoload to detect mistakes. Sure, class names in PHP are case-insensitive but filesystems aren't and most autoloader using the FS to find the right file. To catch such kind of mistakes I would like to implement a fast check in my autoloader to get noted on development instead on production. It's currently only possible with ReflectionClass but this will be much slower as with ::class. Are there any reasons to get the called case of the class instead or the original one? Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Throwable Interface
On 05/23/2015 10:12 PM, Aaron Piotrowski wrote: Hello, I’ve created an RFC for modifying the exception hierarchy for PHP 7, adding Throwable interface and renaming the exceptions thrown from fatal errors. The RFC is now ready for discussion. RFC: https://wiki.php.net/rfc/throwable-interface https://wiki.php.net/rfc/throwable-interface Pull Request: https://github.com/php/php-src/pull/1284 https://github.com/php/php-src/pull/1284 I like this RFC! It's much more intuitive as the current BaseException approve. Some small notes: Backwards Compatibility |Throwable|, |Error|, |TypeError|, and |ParseError| will no longer be available in the global namespace. Where are the new classes and the interface located if it's not in the global namespace or do I muss something? If I remember right the TypeException/TypeError will be thrown in some cases of internal functions with strict argument count. In my opinion a missing argument or to much arguments has nothing to do with the type and should have it's own Exception/Error class. Aaron Piotrowski Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [VOTE] Exceptions in the engine
Am 30.04.2015 um 14:30 schrieb Julien Pauli: On Thu, Apr 30, 2015 at 6:51 AM, Sebastian Bergmann sebast...@php.net wrote: Am 30.04.2015 um 02:50 schrieb Stanislav Malyshev: I like the idea, however we do have the deadline and the deadline has been passed. So I wonder if we can't keep it for 7.1 That means introducing a change in 7.0, changing it and deprecating part of it in 7.1, and removing said part in 7.2/8.0. Makes no sense to me. Either do it now for 7.0 or don't do it. I tend to agree here. If we introduce BaseException, deprecating it one year later (probably) is a bad idea IMO. We could make an exception (sic !) and add the Throwable interface to PHP7, even after feature freeze, because it is an easy pick and having a clear Exception model for 7.0 is to my opinion very important. This would be very great! If I remember right, on base discussion the BaseException vs. Throwable interface was called an implementation detail that can be changed later on. And on vote it was only some weeks before feature freeze so it would be impossible for the Throwable interface to pass before freeze. Julien.Pauli Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC][VOTE] Constructor behaviour of internal classes
Hi Nikita, Dmitry, I think it's a mistake to throw a TypeException on invalid argument count as in this case it has nothing to do with a type. Marc Am 03.04.2015 um 20:48 schrieb Dmitry Stogov: I don' t see any problems. Thanks. Dmitry. On Fri, Apr 3, 2015 at 6:31 PM, Nikita Popov nikita@gmail.com wrote: On Wed, Apr 1, 2015 at 3:31 AM, Dan Ackroyd dan...@basereality.com wrote: Hi Dmitry, Your approach is definitely a better one, and I have no objection to it whatsoever. Sorry, I was too busy to look deeply at each class but I can't see any problems. Nikita Popov wrote: does that mean that the same code using strict_types=1 mode will start throwing TypeException instead of whatever exception type is passed to replace_error_handling? That's going to affect everything isn't it - not just this RFC? However I think that is the correct behaviour. It more closely resembles the behaviour that will be seen in userland code, and is more 'semantically' meaningful i.e. it allows people to tell the cases between the two types of errors apart. It probably bears more thinking about though. cheers Dan $formatInfoList = [ [en_US, {0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree], [en_US, '{this was made intentionally incorrect}'], //valid type but wrong value [en_US, new StdClass] //wrong type ] foreach ($formatInfoList as $formatInfo) { list($locale, $pattern) = formatInfo; try { $mf = new MessageFormatter($locale, $pattern); echo $mf-format(array(4560, 123, 4560/123)); } catch(IntlException $ie) { // A strict type-est person would not want this to catch the case where // the wrong type has been passed, as it's not an exception related to Intl // it's an exception related to the type being wrong. } } PR for throwing TypeException (independently of strict mode) for zpp failures in constructors is here: https://github.com/php/php-src/pull/1215 Will apply it if nobody sees a problem with it. Nikita -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Re: Fix division by zero to throw exception
Am 04.04.2015 um 00:13 schrieb Andrea Faulds: On 3 Apr 2015, at 23:08, Dmitry Stogov dmi...@zend.com wrote: On Apr 4, 2015 12:34 AM, Nikita Popov nikita@gmail.com wrote: Don't think we need to disable compile-time evaluation for 2) and 3). It'll just end up being a compile error in that case. I think if you have 1 % 0 occurring in your code literally, it's better to have the compile fail rather than getting (or not getting) a runtime exception. This is even easier. Andrea, what do you think? I was wondering if that might cause problems if you have a large codebase and some unfixed errors in a few places. If the code isn’t being run, only compiled, then it’d be unnecessary pain. However, the chances of a codebase having numerous undetected divisions by zero, that are obvious at compile-time, aren’t very high. So, failing at compile-time is fine. And, to save another email, I agree with the four items in your summary. Exceptions for negative shift, modulo/intdiv by zero, normal division by zero is +/-INF. :) If the normal division by zero produces +/- INF it's a valid calculation and shouldn't trigger a warning else it should end up in an exception, too. -- Andrea Faulds http://ajf.me/ -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Deprecate setlocale?
Am 01.04.2015 um 18:15 schrieb Dan Ackroyd: Hi, I'd like to get people's feedback for the idea of making setlocale be either deprecated and to be removed eventually or just increasing the warning level against people using it. What if the system is configured with a different locale? OK we could change the locale on startup to C but this could break embedded behaviour and doesn't solve the issue at all. There are some cases where we don't have a good alternative like fgetcsv / fputcsv. The short version of why we should do this is that setlocale breaks things. It is a process wide operation, that is not thread safe on most platforms. Although people use it to alter the way strings are output, it also breaks libraries that are assuming that they are running in a C locale. From my perspective Functionality not related to locale should not be effected by this global - The following bug reports are valid bugs and should be resolved https://bugs.php.net/bug.php?id=59571 - breaks Imagick https://bugs.php.net/bug.php?id=69348 - breaks MySQL - If it's part of the wrapped library it's a bug of this library and should be fixed there Basic PHP functions should be possible to be TS and therefore should ignoring such global configuration else it's impossible to have a TS version of PHP - if there is no alternative functionality we should add one - Non-TS functions should be moved into an extension and don't allow to enable on TS build - Non-TS functions not movable to an extension should be rethink like: - removing the locale based conversion on simple float to string casts - make strtoupper/strtolower etc. to work with ascii only Is't there a very similar issue with fs operations and umask? - Is it possible to have fs operations not related on this non-TS global configuration? https://bugs.php.net/bug.php?id=59571 - breaks Imagick - It's a real bug and should be fixed (not locale based functionality) https://bugs.php.net/bug.php?id=54538 - breaks NumberFormatter - It's a real bug and should be fixed (based on a different safe locale) https://bugs.php.net/bug.php?id=66108 - breaks constants - see comment above about strtoupper https://bugs.php.net/bug.php?id=67127 - breaks DateTime - It's a bug and should be fixed (not locale based functionality) https://bugs.php.net/bug.php?id=69348 - breaks MySQL - It's a bug and should be fixed (non locale based functionality) - Couldn't this one be a security issue And there are quite a few other bug reports where setlocale is doing exactly what it is meant to do, but the unexpected side-effects are catching people out. We have libraries that ship with PHP for formatting dates, numbers etc that actually work, and don't break other libraries. So two questions: i) Are there any reasons why we couldn't or shouldn't plan for removing setlocale at some point in the future? i.e. does it do something that isn't supported by other libraries in PHP? ii) If it's not possible (or desirable) to remove it, how could we increase the warning level against using it? cheers Dan Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] Overwrite return type-hint into a more specific one
Hi internals, On experimenting with return type-hints I noted an inconsistency on overwriting an existing hint to a more specific one. On adding a non existing return type-hint on overwrite it's fine but it's logically the same (this previously was an E_STRICT). http://3v4l.org/YdB8s - works fine (E_STRICT lower then php7@20150401) http://3v4l.org/UDk0n - Fatal error: Declaration of Bar::setTest() must be compatible with Foo::setTest($test): Foo http://3v4l.org/AuOsr - HHVM works fine Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Deprecate setlocale?
Am 01.04.2015 um 20:58 schrieb Stanislav Malyshev: Hi! https://bugs.php.net/bug.php?id=67127 - breaks DateTime This looks like misunderstanding how float-to-string works. If you asked it to put commas as decimal separator, don't be surprised it puts commas as decimal separator. This should be true for number formatting but it's not true for date format. - I'm a german with comma (,) as decimal separator and I have never seen such a comma in microtime separation - There is no way to define this behavior in a date format Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Deprecate setlocale?
Hi Am 01.04.2015 um 21:02 schrieb Stanislav Malyshev: Hi! - make strtoupper/strtolower etc. to work with ascii only This would be a bad idea, however much better idea is to make *system* case folding (i.e. methods, classes, etc.) use ascii-only. Which we already mostly do (see zend_operators.c it explains what's going on). Of course, there can be instances of using the wrong function. In a dynamic language like PHP it's a very normal and basic case handling language features dynamically including the one described in the bug report (Find an upper case constant for the given input). What I mean is that we should have basic functions addressing this. So for example we need a basic function to upper/lower case only ascii characters. Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Overwrite return type-hint into a more specific one
Hi Anthony, Am 01.04.2015 um 21:25 schrieb Anthony Ferrara: Marc, On Wed, Apr 1, 2015 at 2:46 PM, Marc Bennewitz dev@mabe.berlin wrote: Hi internals, On experimenting with return type-hints I noted an inconsistency on overwriting an existing hint to a more specific one. On adding a non existing return type-hint on overwrite it's fine but it's logically the same (this previously was an E_STRICT). http://3v4l.org/YdB8s - works fine (E_STRICT lower then php7@20150401) http://3v4l.org/UDk0n - Fatal error: Declaration of Bar::setTest() must be compatible with Foo::setTest($test): Foo http://3v4l.org/AuOsr - HHVM works fine That's the concept of Variance: https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science) Specifically, that return types can be covariant (subtypes can narrow return types) and parameters can be contravariant (subtypes can widen paramters). So this is valid: class A extends B {} class C { public function foo(A $b): B {} } class D extends C { public function foo(B $b): A {} } In that everything that C::foo accepts, D::foo accepts, but D::foo can accept more. And D produces more strictly (in that anything that can work with a product of C::foo can work with what D::foo produces). We looked into doing this for return types (and all other declarations). However, we ran into some non-trivial problems around compilation. Currently, types are never loaded from a declaration. They are only loaded when instantiated. Therefore, it's completely possible to have a declared class with undeclared type declarations. If the type declaration remains undeclared when you call the method, it's by definition a failed type (since `$obj instanceof UndefinedClass` is always false). Currently in the case of class A extends B {} and B wasn't defined it will be already loaded by autoloader. In the case for $obj instanceof UndefinedClass it can't be possible as $obj was already instantiates and can therefor never be an instance of an currently undefined class. - no autloading needed. If we want to check variance, we need to know about the type at compile time. This brings up an issue that basically makes it impossible to separate code into multiple files without an autoloader. For example: ?php // a.php class A { public function foo(B $bar) {} } ?php // b.php class B { public function bar(A $foo) {} } You couldn't have that be possible without an autoloader, since there's a circular dependency. Sure, we could (and should) special case the doesn't inherit situation, but it's pretty trivial to make a new example which requires an autoloader. So that leaves us with a weird situation: to support the feature (in general), you'd have to use an autoloader or put everything into a single file. That may be OK, but it's also added complexity. To the best of my knowledge, Levi removed variance from the proposal to keep it simple (just like nullables weren't in the proposal): https://wiki.php.net/rfc/return_types#variance_and_signature_validation If you'd like to create a proposal for 7.1 to add variance support to type declarations, I think that would be awesome. It's not terribly difficult, but there are some gotchas (especially around opcache support) and non-trivial tradeoffs involved. Thank you for the really helpful explanation! Now I understand the reasons but I don't have enough experience in C or the engine to make that possible. Would it be possible to support it in the first place only if the return type hints are already known by the engine? Anthony Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Exception hierarchy: open issues
Am 30.03.2015 um 12:58 schrieb Thomas Punt: Hey, Imho TypeException may not be best name for it, as it's also thrown for non-type related error conditions, like mismatched argument count. Would SignatureException be a more apt name for these error conditions? We already have an InvalidArgumentException but this one extends LogicException extends Exception -Tom -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] 回复: [RFC][DISCUSSION] Add preg_replace_callback_array function
I also had a question! Didn't you noticed it? Am 20.03.2015 um 16:49 schrieb Marc Bennewitz: Why not simply allow the callback to be an array, too? Marc Am 21.03.2015 um 09:14 schrieb Xinchen Hui: Hey: On Fri, Mar 20, 2015 at 9:14 PM, Xinchen Hui larue...@php.net wrote: Hey: On Fri, Mar 20, 2015 at 7:53 PM, Alain Williams a...@phcomp.co.uk wrote: On Fri, Mar 20, 2015 at 10:46:58PM +1100, Pierre Joye wrote: On Fri, Mar 20, 2015 at 7:03 PM, Wei Dai zxcvda...@gmail.com wrote: Hi internals, Hi internals, The RFC to add a user-land function for an easy-to-use and reliable preg_replace_callback_array() in PHP is up for discussion: https://wiki.php.net/rfc/preg_replace_callback_array This proposes adding one function: `preg_replace_callback_array()` that is the better way to Implement when there are multiple patterns need to replace. I would love to hear your feedback! :) Any objections? I’ve sent this mail for four days, I don’t know if this RFC needs a vote. If you guys have no objections on this, please review the code and merge it, thanks. Nice job, i like the idea. I am not sure about a RFC or not. It somehow looks like a sane replacement for something we killed (with good reasons). Let see what the other think :) I used s/something/code/ge in a perl script that I wrote a few days ago. Very useful. It would have been a lot more work to do it another way. So: +1 to the ability to do this, regardless of what mechanism is eventually chosen. I also +1 for this. if there is no objections raises, I am going to merge it tomorrow.. merged thanks thanks -- Alain Williams Linux/GNU Consultant - Mail systems, Web sites, Networking, Programmer, IT Lecturer. +44 (0) 787 668 0256 http://www.phcomp.co.uk/ Parliament Hill Computers Ltd. Registration Information: http://www.phcomp.co.uk/contact.php #include std_disclaimer.h -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php -- Xinchen Hui @Laruence http://www.laruence.com/ -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] 回复: [RFC][DISCUSSION] Add preg_replace_callback_array function
Am 20.03.2015 um 09:03 schrieb Wei Dai: Hi internals, Hi internals, The RFC to add a user-land function for an easy-to-use and reliable preg_replace_callback_array() in PHP is up for discussion: https://wiki.php.net/rfc/preg_replace_callback_array This proposes adding one function: `preg_replace_callback_array()` that is the better way to Implement when there are multiple patterns need to replace. I would love to hear your feedback! :) Any objections? Why not simply allow the callback to be an array, too? — Wei Dai -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC][DISCUSSION] Constructor behaviour of internal classes
Am 01.03.2015 um 20:04 schrieb Dan Ackroyd: On 1 March 2015 at 18:35, Marc Bennewitz dev@mabe.berlin wrote: What are the reasons to not make this class instantiable / extendable ? That class handles database state / resources that are not exposed through the userland classes. It's correct in my opinion for it to not be extendible or instantiable. Obviously it would be awesome if they were covered by an interface, to allow testign to be easier, but that's a separate issue. That's definitely better but it's an behavior not possible to implemented in user land code as it would be impossible to get such an object. The same behaviour can seen with the code below. cheers Dan class Foo { private static $internalConstruction = false; public function __construct() { $constructionAllowed = !self::$internalConstruction; self::$internalConstruction = false; if ($constructionAllowed == false) { throw new \Exception(External construction not allowed); } } public static function create() { self::$internalConstruction = true; return new self(); } } $foo = Foo::create(); var_dump($foo); $bar = new Foo(); OK you are right but it's ugly code and the not callable constructor needs to be documented as it's not visible without calling. The following would be the standard way to go: final class PDORow { private function __construct() { // ... } public static function create() { return new self(); } } Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC][DISCUSSION] Constructor behaviour of internal classes
Hi Dan, Am 01.03.2015 um 15:55 schrieb Dan Ackroyd: Hi Internals, This email is to announce the formal opening of discussion for an RFC to clean up the behaviour of the constructors shown by several internal classes. https://wiki.php.net/rfc/internal_constructor_behaviour I really like this RFC as it reduces WTF moments a lot! One note from my perspective: The class PDORow is not instantiable and triggers a fatal errors currently. You propose to change the fatal error into an exception. That's definitely better but it's an behavior not possible to implemented in user land code as it would be impossible to get such an object. To define a class not instantiable in user land would be to define the constructor private/protected. Btw. What are the reasons to not make this class instantiable / extendable ? Thoughts? For reference this was discussed before https://marc.info/?l=php-internalsm=142150339323854w=2 As this RFC targets PHP 7, I plan to open the voting before the cut-off date. cheers Dan -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] Proposal: deprecate undefined passed arguments
Hi all, Because the feature freeze for PHP 7 is near I like to know your thoughts about one more change in passing arguments. Sure this one would introduce one more deprecated message / BC break but this one s for reducing BC break in the future! Currently a caller can pass undefined arguments as much he like. Such passed arguments are only visible by the callee using func_get_args/func_num_args but the need for such function definitions has been gone with argument unpacking feature. The other rare possibility for ignoring passed arguments by callables from functions like array_walk has been gone, too, with the introduction of clusures. By the way we already have internal functions triggering warnings on unknown arguments. This is also an unneeded inconsistency and more it's invisible by the user without testing each function for it. At least simply ignoring passed arguments is a violation as described in the following examples (http://3v4l.org/U2lnf): class Calculator { public function calc($v) { return $v + 1; } } class MyCalculator extends Calculator { public function calc($v1, $v2 = 0) { return parent::calc($v1) + $v2; } } function calcArray(array $values, Calculator $calculator) { foreach ($values as $v) { $v = $calculator-calc($v, $v); // Second argument is wrong !! } return $values; } $ar = [1,2,3]; var_dump(calcArray($ar, new Calculator)); // ignores the second argument var_dump(calcArray($ar, new MyCalculator)); // UNEXPECTED: the second argument will be used Both calculators should be 100% compatible but they aren't as the function calcArray shows. So because of the described issues with the existing code base I like to propose the change to no longer ignore undefined arguments and introduce E_DEPRECATED messages if a function get's an undefined argument. So the user get enough time to fix their code before throwing errors in this case in PHP 8. As this should be consistent over the engine I would propose this change for user defined functions and for internal functions as well. Again, yes this one would introduces one more BC break but first this would be deprecated before disabled and next it's for reducing BC in the future. Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Re: [RFC] Exceptions in the engine
Hi Dimitry, Am 19.02.2015 um 16:13 schrieb Dmitry Stogov: Hi Nikita, I refactored your implementation: https://github.com/php/php-src/pull/1095 I introduced a class hierarchy to minimize effect on existing code. cacth (Exception $e) won't catch new types of exceptions. BaseException (abstarct) +- EngineException +- ParaseException +- Exception +-ErrorException +- all other exceptions I really like this RFC and Exception hierarchy but one very small note: The name of BaseException is a bit to misunderstanding to me as it clashes with the old base exception named Exception, which is by the way very often used as alias (use Exception as BaseExcepton). I know this isn't a technical issue but it reduces readability a code. What are your thoughts about the following names ?: RootException AbstractExcepton snip Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Proposal: deprecate undefined passed arguments
Hi Marcio, Am 23.02.2015 um 21:15 schrieb Marcio Almada: 2015-02-23 16:32 GMT-03:00 Marc Bennewitz dev@mabe.berlin mailto:dev@mabe.berlin: Hi all, Because the feature freeze for PHP 7 is near I like to know your thoughts about one more change in passing arguments. Sure this one would introduce one more deprecated message / BC break but this one s for reducing BC break in the future! Currently a caller can pass undefined arguments as much he like. Such passed arguments are only visible by the callee using func_get_args/func_num_args but the need for such function definitions has been gone with argument unpacking feature. The other rare possibility for ignoring passed arguments by callables from functions like array_walk has been gone, too, with the introduction of clusures. By the way we already have internal functions triggering warnings on unknown arguments. This is also an unneeded inconsistency and more it's invisible by the user without testing each function for it. At least simply ignoring passed arguments is a violation as described in the following examples (http://3v4l.org/U2lnf): class Calculator { public function calc($v) { return $v + 1; } } class MyCalculator extends Calculator { public function calc($v1, $v2 = 0) { return parent::calc($v1) + $v2; } } function calcArray(array $values, Calculator $calculator) { foreach ($values as $v) { $v = $calculator-calc($v, $v); // Second argument is wrong !! } return $values; } $ar = [1,2,3]; var_dump(calcArray($ar, new Calculator)); // ignores the second argument var_dump(calcArray($ar, new MyCalculator)); // UNEXPECTED: the second argument will be used Both calculators should be 100% compatible but they aren't as the function calcArray shows. So because of the described issues with the existing code base I like to propose the change to no longer ignore undefined arguments and introduce E_DEPRECATED messages if a function get's an undefined argument. So the user get enough time to fix their code before throwing errors in this case in PHP 8. As this should be consistent over the engine I would propose this change for user defined functions and for internal functions as well. Again, yes this one would introduces one more BC break but first this would be deprecated before disabled and next it's for reducing BC in the future. Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php Have you checked https://wiki.php.net/rfc/strict_argcount? Only difference is that I'm proposing a warning instead of E_DEPRECATE, but it's still a draft and open to discussion. Maybe you would like to contribute to the RFC before it reaches discussion this week? Wow, nice to see this - didn't noted it before. But I have to questions/notes: 1. Why you throw only a warning and not an error (deprecating this feature first). I don't see the benefit. 2. As I understand it correctly passing unknown arguments will be allowed if the function uses one of the|func_[get|num]_arg[s]()| functions. This looks wired to me as the caller should not know the body to know how a function can be called and because of the dynamic nature of PHP this check isn't possible in all cases as you already noted. Additionally such strict check is for detecting wrong calls but this detection doesn't work with code like this: https://github.com/zendframework/zf2/blob/master/library/Zend/Cache/Storage/Adapter/Memcached.php#L213 In my opinion functions using |func_[get|num]_arg[s]() |to implement variadic arguments are totally outdated and should be refactored using new semantic. I also think such code isn't used very often and deprecating it + removing later on (PHP 8) will give more than enough time to update it as it's simple to find and simple to fix. Also to previous example given for ZF2 shows that the function |func_num_args()| have it's rights to exit but i'm unsure about |func_get_arg[s]()|. Marc
Re: [PHP-DEV] Remove $this from incompatible context
Hi Am 13.02.2015 um 08:48 schrieb Stanislav Malyshev: Hi! there should be no bc break as the API doesn't change and the method produces the exact same result as before. Sorry, this makes no sense to me. You claim that if you changed the method code to do different thing it should continue working as if you didn't change it? Why? I just don't get it. It's not a good thing to magically change the method API in base of a method body that's not port of the API. magically change the method API? What are you talking about? You changed the code, not magic. Sorry it wasn't clear. I hope I will now: The static modifier for methods is part of the method signature and method body isn't. (That's way interfaces doesn't describe method bodies but signatures) The static modifier defines a method as static and therefore defines the method is callable using ::. What I mean with magically is that you like to define a method as static without the static modifier in base of the method body but the body isn't part of the signature. Now if you change the method body only without this very special knowledge into something using $this you break all code that calls the method statically. So for me a +1 to throw an E_DEPRECATED error in this case and remove this feature in PHP 8. This will inform existing applications about the wrong call and provide enough time to be fixed. Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Remove $this from incompatible context
Hi Stas, Am 12.02.2015 um 22:31 schrieb Stanislav Malyshev: Hi! class A { // This is an *instance* method, but it doesn't actually use $this. // This kind of usage is very common in PHP 4 era code, where // static annotations weren't used function test() { echo foo; } } class B { function test2() { // This call would be forbidden because it assumes $this of class B, when // calling an instance method of class A. However A::test() does not actually // use $this! A::test(); } } IMHO, this should work. Maybe issue E_STRICT, but even then I'd think it's not really necessary, I can't see any purpose E_STRICT serves in this case - since $this is not used, no potential bug is averted, as the code works exactly as it was supposed to be working. Such code will break, not in the first place but later on! You propose that every instance method not using the variable $this internally will be magically a static method and can never ever be changed to use $this without an bc break. snip Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] PHP6 artifact - binary strings
Hi all, Since PHP-5.2.1 we have an artifact of PHP-6 in the engine means we can define binary strings but such definitions haven't any effect. So what we can define is the following: $str = str; $bin = bb\0i\0n; $str2bin = (binary)$str; One of the biggest issue is that currently ALL strings will be handled as ASCII-7 compatible strings on type-juggling but they aren't. It would be very appreciated if PHP could respect such binary declaration: * use binary string comparison on compare a binary string to any other string * don't convert binary strings into integers on array keys * allow bitwise operators on binary strings without casting to integer I don't wont to open such unicode nightmare as it was planned for PHP-6! In my opinion the above operator changes are enough and therefore internal functions doesn't need to be changed in the first place. The only changes *could* be done to functions reading/parsing data to be auto marked binary like: unpack, stream reading functions opened with fopen + b ... I don't have enough zend experience and therefore I would like to know how complicated it would be. Thoughts? Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Static Closures and PHP 7
Am 20.01.2015 um 18:58 schrieb Levi Morrison: Internals, Last year I fixed the behavior of closures in a few regards, which were included in PHP 5.5.14 and 5.6 (unsure on exact version): - Static closures properly use late-static binding on `static::` calls from inside static methods. - Non-static closures in static methods are automatically promoted to static closures The first item is undoubtably a bug-fix (see http://3v4l.org/lVenA for an example). The second item, however, is a bit more questionable. Take as an example this code: http://3v4l.org/YMYeu (located at bottom of email as well). When in global scope using an anonymous function with a $this-ptr does not error, but when we are in a static method there is a warning at bind-time and a fatal when the method is called. Before my changes I could have said this was a bug with confidence. After my change, however, it means that the closure is implicitly static and therefore cannot use a $this pointer. My patch didn't break anything, but allowed people to use late static binding in non-static closures inside of static methods (I recommend reading that sentence again). Logically, I am surprised by this behavior. I would think that anything permissible for a closure in global scope is also permissible for a closure in static scope. What do you guys and gals think? It should indeed have the same object behavior as closures in global scope. Before bind: Fatal error: Using $this when not in object context After bind: valid But static:: and self:: should work the same as on static closures. ?php class A { function hi() { return hello; } } // in global scope $f = function() { return $this-hi(); // no warnings }; $a = new A(); $g = $f-bindTo($a); // no warnings echo $g(), PHP_EOL; // no warnings class B extends A { // in a static function static function make() { return function() { return $this-hi(); // fatal error when called }; } } $h = B::make(); $i = $h-bindTo($a); // warning echo $i(), PHP_EOL; // fatal error Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Skipping parameters take 2
Am 19.01.2015 um 19:48 schrieb Adam Harvey: On 17 January 2015 at 18:04, Andrea Faulds a...@ajf.me wrote: For consistency with list(), we could also just put nothing: foo($bar, , $baz); Which is like: list($bar, , $baz) = $arr; Thoughts? That was Stas's original, original proposal way back when. I argued then for having default as a placeholder, and still would today — in the case where a function with, say, ten optional parameters[0] is being called and eight of them should be the default, I think it's a bit rough for somebody inheriting that code to have to count commas. Having a token increases readability, IMO, and costs us nothing except a few keystrokes, which isn't going to break the camel's back in a language that requires function each time you declare a function. Adam [0] Yes, that's probably poor API design. You and I both know someone will do it, though. :) Pros Cons _Simply skipping the argument out:_ pro: - same syntax as skipping entries used by `list` con: - hard to read and to differ from mistakes - not an option for inheritance _Using the keyword `default`:_ pro: - better to read and to differ from mistakes - usable on inheritance con: - different syntax as `list` - not possible as alternative syntax for `list` as it has no default naming _Using a special character:_ pro: - better to read and to differ from mistakes - usable on inheritance - possibly an alternative syntax for `list` (for consistency) con: - different syntax as `list` - Not a good character found for it, yet _Named Parameters:_ pro: - readability (If caller is not required to call as assoc array) - not an option for inheritance con: - paramter skipping is a side product with possible edge cases - Adds variable names to be part of the API - implementation complexity In my opinion plain skipping parameters is a nice addition to PHP even if named arguments will be introduced. A special character would indeed the best option but as long as there is no good character it's not an option. @Stas: Any news on using default on inheritance ? Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Inconsistencies in callable, call_user_func and direct variable calls
On 20.01.2015 22:46, Nikita Popov wrote: On Tue, Jan 20, 2015 at 9:54 PM, Marc Bennewitz dev@mabe.berlin mailto:dev@mabe.berlin wrote: valid for call_user_func[_array] and callable type-hint but invalid for for direct variable calls: - string MyClass::staticFunc - string self::staticFunc - string static::staticFunc - string parent::func - string parent::staticFunc see http://3v4l.org/1oSO3 Thoughts ? I would prefer deprecating this alternative notation instead of adding more support for it. The [$class, $method] form is the canonical form we support everywhere and which is consistent with the [$obj, $method] callbacks. There's no point supporting another alternative notation, especially if it was effectively unusable for a while now already. I don't think removing this is an option because of a big BC for no reason. Additionally the string alternative have some advantages: - better usable in configurations - return syntax of third argument of is_callable - ... Nikita Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] Inconsistencies in callable, call_user_func and direct variable calls
valid for call_user_func[_array] and callable type-hint but invalid for for direct variable calls: - string MyClass::staticFunc - string self::staticFunc - string static::staticFunc - string parent::func - string parent::staticFunc see http://3v4l.org/1oSO3 Thoughts ? -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Skipping parameters take 2
Hi Robert Am 16.01.2015 um 11:04 schrieb Robert Stoll: Hi Stas, -Ursprüngliche Nachricht- Von: Stanislav Malyshev [mailto:smalys...@gmail.com] Gesendet: Mittwoch, 14. Januar 2015 21:26 An: Marc Bennewitz; internals@lists.php.net Betreff: Re: [PHP-DEV] [RFC] Skipping parameters take 2 Hi! Is it possible to use the default parameter on inheritance? class Bar { function foo($a='a', $b='b') {} } class Baz extends Bar { function foo($a=default, $b=default) { // do something parent::foo($a, $b); } } It's not part of the original proposal, and I'm not sure how easy it would be to implement, but it sounds like a nice extension, I didn't think about it. Since the RFC is already in vote, I won't change it now, but I'll look into if it's possible to do it, and if the RFC is accepted, and it proves possible, I'll propose it separately. -- Stas Malyshev smalys...@gmail.com This would be quite a nice feature, even if this RFC does not pass. Just as hint, there are ambiguous case which need to be considered: interface A{ function foo($a=1); } interface B{ function foo($a=hi); } class C implements A, B{ function foo($a=default){} //what would be the default value? } Cheers, Robert The default value have be the one of the parent. if there is no parent you have the following options: * Syntax error (I prefer) * If defined use from interface * If ambiguous: * Syntax error * Choose one (bad in my opinion) Marc
Re: [PHP-DEV] [RFC] Scalar Type Hints v0.2
Am 15.01.2015 um 20:45 schrieb Marcio Almada: Hi, I would like to call everyone's attention, specially people contributing directly to this RFC series, to what S.A.N just said: Many developers PHP offers dual syntax: 1. Strict function bar(int $num){} 2. Lax function bar((int) $num){} Maybe it makes sense to put this option on the ballot if it passes a vote, it will be possible to put an end to the discus? This idea has been **so recurrent** and yet systematically ignored by RFC owners. Why? I think that we need to baby step and try to approve coercive type declarations first and decide upon a possible stricter type check later: How a bout a reboot of what ircmax...@php.net already started in https://wiki.php.net/rfc/parameter_type_casting_hints for v0.3? PS: Please, let's not fall into the mindset of if v0.2 is not a good idea then v0.1 instantly becomes more acceptable, we still have time to try some alternatives. A function only defines the arguments and types it requires and not where the arguments comes from. Casting is part of Where the arguments comes from Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Scalar Type Hints v0.2
Am 14.01.2015 um 23:39 schrieb Andrea Faulds: Hi Marc, On 14 Jan 2015, at 19:01, Marc Bennewitz dev@mabe.berlin wrote: 1. Inconsistencies of ZPP and explicit casts In my opinion it should be the same if you call a function in weak type mode and calling a function in strict type mode with explicit cast. But that would require to remove inconsistencies of ZPP and explicit casts. Explicit casts and implicit casts have different behaviour, and that is definitely a good thing. Implicit casts can and should fail if the conversion isn’t sensible. Explicit casts aren’t supposed to fail. That's a big problem for the strict type mode because of you have to explicit cast to pass function signature which would result in a much unsafer behavior were you originally wont a strict behavior. The only way to be safe would be to use extra function calls for casting. 2. Only one choice for the language In my opinion scalar types should be hinted strict and the caller of an API have to be sure to pass the right types. The caller have to know about the function he calls and he already should know what the function expects. This is the point were the caller have to know the type of an expected argument and he should know his own types. So he is the one how can pass the variable or make an explicit type cast. This is all very well and good, and strict typing has its advantages, but there are a lot of people who do *not* want to have to deal with a strictly-typed API. It's only a personal feeling for scrict typing but it requires casting to be fixed. But I have to agree with that casting is part of the caller with or without this choice. The library author only defines the type he requires but the caller is the one have have to do so. Week typing in this case only helps the caller to automatically cast. 3. Reserved words I don't like it adding so much reserved words. This doesn’t add any reserved words. It prevents the usage of some names for class names. Preventing usage of some names means the same as reserved names at least in the contest of class names. As I understand it correctly the reservation is because of naming collisions on type-hints with scalars and classes/interfaces. Why not adding these types as classes (marked final and not allowed to be initialized for now)? Because then you’d have to do this at the top of every single file: use php\typehint\int; use php\typehint\float; use php\typehint\string; use php\typehint\bool; Considering how much people seem to dislike the idea of using declare() for strict typing, I can see how poorly that would go down. Such types should be on the root namespace. So the only difference would be a backslash and only if you are within a namespace. And to reaped myself you can do vary useful: // internal pseudo code class Scalar {} interface Numeric {} class Integer extends Scalar implements Numeric {} class Float extends Scalar implements Numeric {} class String extends Scalar {} class Array implements Traversable {} // users code function increment(numeric $num) { return $num + 1; } function incrementInt(integer $int) { return $int + 1; } function incrementFloat(float $float) { return $float + 1; } // in namespace function increment(\numeric $num) { return $num + 1; } function incrementInt(\integer $int) { return $int + 1; } function incrementFloat(\float $float) { return $float + 1; } More importantly, this would be inconsistent with our existing type hints like array and callable. It would only be inconsistent if you don't think it through end but sure it's more work. I have no idea how much. On calling a function in week mode one or more magic methods could be used to add auto cast behavior like: public function __toInt(); public function __toFloat(); public function __toString(); // it will be called already public function __toArray(); // Not part of this RFC public function __toInstanceOf($name); // Will be called if no one of the other pass 4. Only one naming I dislike the proposed aliases. The type names should be defined once without aliases and the manual and error massages should be changed to be consistent. In an ideal world we would only have the short or long form, sure. But this isn’t an ideal world, and PHP doesn’t have compile-time validation of type hints. It would be too easy to write foo(integer $bar) and miss that it is broken if the function isn’t called. Please let us make PHP more ideal ;) Your argument is nonsense. As long as you never test your (unittest or manual) you can't be sure to work well. The same argument could pass for current type-hinting. If that argument is serious you have to eg. automatically fix type errors in class names. Btw. IDEs already warn if you use something undeclared project wide. I don’t think having both int and integer is really a problem. It’s not going to cause confusion, they are obviously the same type. Coding style guides will mandate
Re: [PHP-DEV] [RFC] Skipping parameters take 2
Am 14.01.2015 um 20:21 schrieb Adam Harvey: On 14 January 2015 at 11:15, Marc Bennewitz dev@mabe.berlin wrote: But I think adding default as new keyword is a big BC break! Default already is a keyword: http://php.net/switch. There's no BC break. OMG you are right - my fault I personally also don't like it and asked myself why can't the parameter simply skipped? That was in the original proposal, but counting commas is pretty lousy if you're skipping more than one or two parameters. Having a keyword makes it more readable. Adam -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Scalar Type Hints v0.2
Hi Andrea, I have some notes about this RFC from a users POV with only little knowledge about internals. I didn't read 100% of the theads of this RFC so I'm sorry if some notes of this email was already discussed. 1. Inconsistencies of ZPP and explicit casts In my opinion it should be the same if you call a function in weak type mode and calling a function in strict type mode with explicit cast. But that would require to remove inconsistencies of ZPP and explicit casts. 2. Only one choice for the language In my opinion scalar types should be hinted strict and the caller of an API have to be sure to pass the right types. The caller have to know about the function he calls and he already should know what the function expects. This is the point were the caller have to know the type of an expected argument and he should know his own types. So he is the one how can pass the variable or make an explicit type cast. To do so see [1] 3. Reserved words I don't like it adding so much reserved words. As I understand it correctly the reservation is because of naming collisions on type-hints with scalars and classes/interfaces. Why not adding these types as classes (marked final and not allowed to be initialized for know)? Than you can use the already existing standards of classes as type-hints. This would allow you using your own class of a different namespace with the same name and would reduce BC break drastically. The only consequence would be that you have to reference the root namespace or import (use) the classes of the root namespace to use the type-hints. As sugar it should be possible to use inheritance and polymorphism to better hint what you really need. E.g.: class Integer extends Scalar implements Numeric 4. Only one naming I dislike the proposed aliases. The type names should be defined once without aliases and the manual and error massages should be changed to be consistent. Because of PHP internally already allows different names this should persist to be BC safe but should be reviewed and documented what is the real type name and what are aliases. The aliases could be deprecated in another RFC. Btw. The type float is used also as double and real. I don't see if these aliases are supported in your RFC or not. Marc Am 14.01.2015 um 01:16 schrieb Andrea Faulds: Good evening, I’ve made some quite significant changes to my Scalar Type Hints RFC, and bumped its version to 0.2. Here: https://wiki.php.net/rfc/scalar_type_hints This is a new thread because I’ve made a significant revision to the RFC, so it’d be sensible to separate discussion of the updated RFC from the v0.1 RFC. Please tell me your thoughts. Thanks! -- Andrea Faulds http://ajf.me/ -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] [RFC] Skipping parameters take 2
Hi Stas, I really like this RFC. It makes it simple to use defined defaults without the need to know about them of to updated. But I think adding default as new keyword is a big BC break! I personally also don't like it and asked myself why can't the parameter simply skipped? function foo ($a='a', $b='b') {} foo(); foo($a); foo(, $b); foo($a,); foo(,); Is it possible to use the default parameter on inheritance? class Bar { function foo($a='a', $b='b') {} } class Baz extends Bar { function foo($a=default, $b=default) { // do something parent::foo($a, $b); } } Marc Am 02.09.2013 um 09:17 schrieb Stas Malyshev: Hi! I've finally took some time to revive the skipping parameter RFC and patch. For those who doesn't remember what it is please see: https://wiki.php.net/rfc/skipparams TLDR version: The idea is to allow skipping parameters in function with optional arguments so that this: function create_query($where, $order_by, $join_type='INNER', $execute = false, $report_errors = true) can be called like this: create_query(deleted=0, name, default, default, /*report_errors*/ true); Instead of trying to remember what the defaults are. The patch is here: https://github.com/php/php-src/pull/426 Any comments or feedback on the RFCs and the code are welcome, especially pointing out the cases where it may not work (which means we need more phpt's there :) -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] persistent zval
Am 10.12.2014 um 09:53 schrieb Stanislav Malyshev: Hi! Why? There is a reference counter, which should be increased on put a value into persistence and on removing a value from persistence decrease it. So the GC could handle unreferenced zvals. Because memory which is allocated by the engine is freed at the end of the request. You could copy the memory values but by then unless your zvals are pretty simple you'll be pretty close to what the serializer does, so no really big win there. The only advantage would be that when you use it, if you're really careful, then you can use the data without reallocating memory and freeing it. But it's not just putting a flag/refcount on it, it requires some copying before that and some careful setting of the refcounts too. So in theory, it can be done at least for scalars and arrays (objects would be a problem since they need class, and what if the class changed?) but it's not trivial. Thanks for the explanation! I'll experiment with it for scalars as extension. Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
[PHP-DEV] persistent zval
Hi all, Is it possible to make a zval persistent? Currently I only found persistent resources or internal references used in objects. It would be very great for some userland applications to make a value persistent whatever type it is. Like the internal global persistent_list but this one is used for persistent resources and I don't see how to use this one for zval's directly. Additionally it's used internally with unknown hashes so it could be dangerous to export it to userland. Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] persistent zval
Am 09.12.2014 um 20:03 schrieb Sara Golemon: On Tue, Dec 9, 2014 at 10:58 AM, Marc Bennewitz dev@mabe.berlin wrote: Is it possible to make a zval persistent? Nope. Why? There is a reference counter, which should be increased on put a value into persistence and on removing a value from persistence decrease it. So the GC could handle unreferenced zvals. Example: persist_set($key, $value); persist_get($key); persist_has($key); persist_list(); // list of persistent values -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Static functions Vs Nonstatic functions
Please read : http://grokbase.com/t/php/php-internals/14acs23cpe/disallow-non-static-method-calls-with-self-static-in-php-7#20141026ct1np9k82bte2m9k9rtmq1c2jr Am 28.11.2014 um 20:29 schrieb Carlos Rodrigues: PHP has evolved a lot in recent years but we still can't have a static and a nonstatic function with the same name: class A { function bla() { echo 'normal'; } static function bla() { echo 'static'; } } A::bla(); ## ERROR: Cannot redeclare A::bla() And also PHP supports calling static functions as if they were not static: class B { static function bla() { echo 'how come it works'; } } $object = new B; $object-bla(); It confuses programmers that came from other languages, prevent APIs from having meaningful names on static methods and have no other benefit than supporting PHP 4 code. I'd appreciate if anyone with sufficient knowledge/influence helped me suggest this change to the maintainers. IMHO, static and nonstatic functions should be stored in different places. And if someone relies on this, one should use magic methods __call and __callStatic instead. Thanks for your time and patience, Carlos Rodrigues car...@jp7.com.br -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php