14 ms·
PHP7 Gains Scalar Type Hints
- Danack 12y agoTo explain the slightly horrible fact that there are two modes, strict and weak with strict mode being enabled on a per file basis; people just couldn't agree on whether the types should be strict or if they should use PHP's existing coercion rules. (Or even a 3rd new set of conversion rules, but lets ignore them). Having an optional mode per file allows: People who want to write code with strict types can do so. People who want to write code with weak types can do so. People who want to write code without these new fangled types can continue to do so. All without any issues of compatibility between running code on the current version of PHP and what will be the next one, and without any compatibility issues for libraries that are solely written in one mode, being used in applications that are written in the other mode. \o/ To be honest, I'm completely in the strict camp - but it's awesome that we've gotten a solution that should allow everyone to use the mode they want, without splitting the PHP ecosystem.
- TazeTSchnitzel 12y agoThe big benefit is you don't end up with "weakly-typed", "strongly-typed" and "untyped" APIs. There are just "typed" and "untyped" ones, and you can choose the behaviour that suits you best.
- ars 12y ago> To be honest, I'm completely in the strict camp Can you explain why? Are you using PHP in a web context? Because everything from the web is a string. So wouldn't it make the most sense to let the functions using the web data coerce to integer, and just work? How does putting (int) before the arguments to function help anything? I actually liked Ze'ev's proposal because it let you be weak while making sure you did not coerce obviously bad data. Anyway, as a member of the strong camp, can you explain?
- bad_user 12y ago> Because everything from the web is a string. I would start by saying that everything, regardless of domain, is just a stream of bits. Which is completely useless, just like your assertion. And I know what you meant, but you're also wrong. A JSON object is only a string before being interpreted. An x-www-form-urlencoded is actually a map in which values can be arrays instead of primitives. Such forms often correspond to domain models with a clear definition. There's also no such thing as "obviously bad data". All data is good in the proper context, therefore automatic conversions that try to make this distinction do not make sense. I don't necessarily know how PHP behaves, but in another popular language there's a world of difference between "077" and "77". There's also a world of difference between integer, floating point and fixed point and the details are never irrelevant.
- ars 12y ago> therefore automatic conversions that try to make this distinction do not make sense. You have to convert it somewhere. I don't see how the caller converting it is any better than the recipient doing it. Having the caller do it seems quite pointless when the recipient is anyway doing it. Your answer about how everything is bits was quite useless since you completely missed the point. Your input is a string, you have to convert it someplace. Weak mode has the recipient do it. Strict mode you have to do it yourself, and then the recipient double checks. I see no value in the second option - the actual conversion in both cases is identical. But Danack disagrees, so I asked him to explain. Your answer was not helpful at all.
- bad_user 12y ago@ars, you completely missed my point. Lets go over it again. Tell me how should the following things convert: 77 077 77.0
- ars 12y agoI GOT your point. I don't care about your point because it is not the question I am asking. Why are you answering something I did not ask? I am asking why does Danack prefer strict mode. There is absolutely nothing in my question that cares about the specific details how you convert bits to types, other than that you do. My question is entirely about WHO does the conversion. NOT about the conversion itself. (Oh, and the thing about bad-data has a defined meaning that went over your head because you are not familiar with the debate here. In this context bad-data means data loss on conversion. So "1" to 1 is fine, but "1 a" to 1 is not.)
- amyjess 12y agoWhat happened to PHP6?
- leeoniya 12y agomost of it was rolled into 5.4. i think some of the more contentious unicode parts were dropped.
- agumonkey 12y agoIt got a call from ECMAScript 4.
- Washuu 12y agoIt was partly voted to skip the number 6 due to the numerous books available for sale that covered the original PHP 6 draft. This would cause confusion for people attempting to learn the new specification. Examples on Amazon: http://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=PHP%206 http://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3D... The vote: https://wiki.php.net/rfc/php6 https://wiki.php.net/rfc/php6
- aarondf 12y agoFrom the voting page: > The decimal system (or more accurately the infinite supply of numbers we have) makes it easy for us to skip a version, with plenty more left for future versions to come. Hard to argue with that!
- TazeTSchnitzel 12y agoPHP6 was supposed to be this all-singing all-dancing Unicode support release. It dragged on for years but didn't get finished due to various issues, and in 2008 they decided to just scrap it and roll what they could salvage into 5.3 Since PHP6 died, it made sense to avoid confusion and not name the new major version 6, since we'd then have two different PHP 6es. This is not unlike what happened with ECMAScript 4.
- some_furry 12y ago
- jkoudys 12y agoFinally! I had a lot of concerns about this, but I think they're mostly answered by the discussion. I do like the way union types work (at least nullable types) in Hack, but I think they existing `foo(int $param = null)` approach is fine for 99% of cases, and those that it doesn't work for can go back to type-checking at the top of the function (ie do what we have to do for all scalar types right now). While I understand the optional strict mode, I do find it quite confusing: it looks similar to javascript's 'use strict';, and at first glance it sounds like it should be similar to `error_reporting(E_STRICT)`, yet somehow scoped to the <?php ?>. Personally I like the `strict namespace` approach they proposed the most. The argument against is that it will read like everything in that namespace is strict, when it's actually limited to the file, but I think it's pretty clear if I read in a.php `strict namespace Qaribou;` and in b.php `namespace Qaribou;`, that a.php is strict and b.php is not. I really don't see the ambiguity there.
- leeoniya 12y agospeaking of phpng, it now scores 1s better on the wordpress unit tests than just 3 month ago: https://wiki.php.net/phpng https://wiki.php.net/phpng
- arenaninja 12y agoHooray! \o/ I haven't had a use for this yet, but I'm always amazed by how PHP manages to move forward without breaking BC.
- AlexMax 12y ago> I haven't had a use for this yet, but I'm always amazed by how PHP manages to move forward without breaking BC. This. If I were a Python developer (of the language itself), I would be paying very close attention to how PHP has handled deprecation and breaking changes.
- TazeTSchnitzel 12y agoThere's been an effort with PHP 7 to try and avoid a Python 2/3-style situation. The PHP 5 to 7 jump should be much smaller than from 4 to 5.
- Danack 12y ago>The PHP 5 to 7 jump should be much smaller than from 4 to 5. And also the jump from 5.4+ to 7 is probably smaller than the jump from 5.2 to 5.3. Although I think the PHP project does need to support versions for longer, the adoption rate of 7 is going to be quite rapid due to the low barrier of doing it, and the massive performance and language gains.
- imakesnowflakes 12y agoLike this? http://www.reddit.com/r/lolphp/comments/2wse9i/just_ran_into_this_one_php_backward_compatibility/ http://www.reddit.com/r/lolphp/comments/2wse9i/just_ran_into...
- Latty 12y agoReally? I see it as the exact opposite. Sure, Python added some pain from 2-3. They did so to fix the main flaws in the language and remove deprecated stuff. The language is now far better and the cost has mostly been paid. The alternative is the PHP approach where everything hangs around for ever, and everyone is using deprecated stuff, everything is named weirdly and lots of extra gunk has to be shoved in to try and make it work in a sane way because "we didn't want to break anything". I understand why some people prefer that, and why it's the way most languages go (Java does the same thing, just with way less movement in general compared to PHP), but it means that the language gets worse over time. Eventually, if you don't do that breaking change, the language will get replaced by something that doesn't need all the cludge.
- ZeroCoin 12y agoI love PHP. I think of it as the English language of programming. Picking and choosing all of the best bits from every other language, and bastardizing them into it's own everyday use.
- brianpgordon 12y agoHave you heard of https://en.wikipedia.org/wiki/Stockholm_syndrome https://en.wikipedia.org/wiki/Stockholm_syndrome?
- jhall1468 12y agoI think the part where you said "best bits" is debatable.
- draders 12y agoI too love PHP!
- wyager 12y agoIf I cut off the limbs of a bunch of athletes and glue them together, it doesn't make a better athlete.
- tomschlick 12y agoDepends on the sport.
- Padding 12y ago
- 1ris 12y agoCan somebody explain this to a non-phper? So PHP got strict types, but only for Scalars (Ints and floats) and they can be enabled on a per-file basis. Right?
- TazeTSchnitzel 12y agoPHP has had type hints for classes for more than a decade now: function foobar(MyClass $foo) { // do stuff } foobar(new NotMyClass()); // throws an error This just adds type hints for the scalar types (integer, float, string and boolean). Since PHP has a long tradition of weak typing and this is what PHP's built-in and extension functions use, weak is the default behaviour, allowing some conversions: function foo(int $x) { var_dump($x); } foo("12"); // produces int(12) foo(null); // throws an error But, you can optionally turn on a strict type-checking mode for scalars on a per-file basis, which doesn't allow conversions: <?php declare(strict_types=1); function foo(int $x) { var_dump($x); } foo("12"); // throws an error foo(null); // throws an error
- deleted 12y ago[deleted]
- Danack 12y agoPHP has had type-hints for parameters for several version, but they could only be used for classes. The new types-hints cover the 'scalar' values (aka not object) and are int, float, string and bool. They allow a function to declare what they types of the variables it receives should be like: function foo(int $x) { // x is guaranteed to be an int. } The type-hinting for scalars has two modes: * strict - the parameter passed to the function must be of the exact* type. * weak - the parameter passed to the function will be converted to the correct type. The strictness depends on what mode PHP was in when the function was called. This is the right choice as it: * Allows library authors to write their code in either strict or weak mode. * End-users to write their code in either strict or weak mode. Or even without using scalar type-hints. * End-user to be able to choose when they are writing their code do they want their variables to be converted to the type expected by the library automatically, or do they want PHP to give them an error if they accidentally pass the wrong type of variable to a function that is expecting an int. *except for some widening rules, e.g. you can pass an int where a float is expected, as ints can be converted into float without data loss (for ints less than 2^53).
- awalGarg 12y agoYay! <3 PHP. Also, the moment I read declare(strict_types..., for some reason "use strict"; from ECMAScript flashed in front of me :D
- some_furry 12y agoSame idea, except `use \Foo\Bar\Baz as SomeAlias` is already reserved for namespaces.
- TazeTSchnitzel 12y agoAlso, we already have use strict; as an easter egg ;)
- scintill76 12y agoExactly how do you trigger the easter egg, and what does it do?
- johnny22 12y ago$ php -a php > use strict; PHP Fatal error: You seem to be trying to use a different language... in php shell code on line 1
- some_furry 12y agoOkay, I have to admit, that is pretty amusing. :)
- tambourine_man 12y agoThat made my day, thanks
- awalGarg 12y agoOh my! That deserves another HN post in itself! <3
- eduard44 12y agoGood. Now I just need to wait for PHPStorm to support them ;)
- TazeTSchnitzel 12y agoSubmit a feature request! ;)
- spion 12y agoI can't find it anywhere in the document - are these statically checked types or just run time checks (contracts)?
- TazeTSchnitzel 12y agoRuntime (like PHP's existing type hints), but they could be checked statically by IDEs and such. One benefit of strict mode is that it enables much better static checking than weak mode, because validity is determined by type and never value.
- Chintagious 12y agoWow, interesting: "Whether or not the function being called was declared in a file that uses strict or weak type checking is irrelevant. The type checking mode depends on the file where the function is called." That means that my function can have a parameter defined as an int in its strict file, but if it's called from outside of it, anything can still be passed to that parameter, right? I'm not sure how I like that. What if you're passing input from class A into class BStrict then using BStrict to call a function in CStrict? BStrict and CStrict are defined as strict, where A is not. Would BStrict then be the one throwing the error because the "caller" is the issue? From the description it seems that the parameters are effectively ignored in BStrict when A calls it. Am I missing something or does this sound iffy? Edit: Link for quote - https://wiki.php.net/rfc/scalar_type_hints_v5#parameter_type_declarations https://wiki.php.net/rfc/scalar_type_hints_v5#parameter_type...
- MAGZine 12y agoSounds right to me. If you're using untyped code, you shouldn't care what you're calling into. strict mode should only apply when both parties agree to it, otherwise strict mode would be the default and you'd have to explicitly mark code as unstrict.
- TazeTSchnitzel 12y ago> That means that my function can have a parameter defined as an int in its strict file, but if it's called from outside of it, anything can still be passed to that parameter, right? Not at all. It's "weak" typing, not no typing. A small set of convertible values can be passed and will be converted to the type you asked for, while other values error as usual. See the rest of the RFC.
- Chintagious 12y agoYou're right, I see that now. That's why they went into describing type conversions too. Thanks for the insight!
- pbiggar 12y agoThat's right, the PHP community _votes_ on language features.
- TazeTSchnitzel 12y agoThough there is a lot of controversy about who is allowed to vote. Currently it's anyone with a php.net account, which is: * People who have commit access to git/svn * Documentation contributors * Documentation translators * PEAR package maintainers * PECL package maintainers * Very few "community representatives"
- pbiggar 12y agoAgreed. I think I still have a vote, and I haven't been involved in PHP for about 6 years.
- chx 12y agoWhile I won't go even close to the PHP internals list, deciding on the community representatives will be... interesting. Drupal, which http://w3techs.com/technologies/details/cm-drupal/all/all http://w3techs.com/technologies/details/cm-drupal/all/all powers 2% of the web has an army of subsystem http://cgit.drupalcode.org/drupal/tree/core/MAINTAINERS.txt http://cgit.drupalcode.org/drupal/tree/core/MAINTAINERS.txt maintainers. If you open the gates, whom of them will be allowed to and who won't? Fascinating.
- TazeTSchnitzel 12y agoGenerally the idea is to give the head of the project a vote.
- wvenable 12y agoSince PHP has switched to community voting, the language has expanded smartly by leaps and bounds while maintaining a great degree of compatibility.
- cwyers 12y agoIs this compatible with what Facebook has done with Hack?
- TazeTSchnitzel 12y agoThere's no fundamental incompatibility. Hack files don't use <?php tags, they use <?hh tags. I'm sure Facebook will make HHVM handle PHP type declarations alongside Hack type declarations, though exactly how they'll interact remains to be seen.
- smt88 12y agoThis is going to depend on how Facebook decides to maintain their PHP spec. They might decide to fork it for all we know. But honestly, if you're using HHVM already, you should have as much tooling/documentation as you need to switch to Hack itself within the next year or so, so all this PHP discussion is moot.
- imakesnowflakes 12y agoDoesn't change anything. It is still shit. You can throw all new features into the language and as long as the rotten core remains, you are not improving the language much. Remember, a chain is only as strong as the weakest link. And that is disregarding the fact that these new features are being implemented by the same persons (students and hobbyists; generally people who have zero experience outside of PHP, and in some cases, even very little programming experience at all) who have coded so much wtf's into the languages. Seriously, one should really stay away from PHP if possible...So don't give PHP 'another try' because of all these new stuff...
- debaserab2 12y agohttp://en.wikipedia.org/wiki/No_true_Scotsman http://en.wikipedia.org/wiki/No_true_Scotsman And yet it runs so much of the web...
- e-tron 12y ago"and as long as the rotten core remains" <-- care to explain more on this ?? And while you are explaining that i would like to remind you that there are no perfect languages out there..
- Apofis 12y agoTry Facebook's Hack if you want all the nice stuff of PHP and modern language features. PHP still beats the pants out of just about any other language out there in the ease of use department if you want to build websites and is fairly simple to learn. Once people pick up PHP, then they usually start exploring other languages that are more involved and strict. All this PHP hate is really discouraging to beginners.
- imakesnowflakes 12y ago>PHP still beats the pants out of just about any other language out there in the ease of use department.. This is not true. Why is it easier than, say, Ruby >Once people pick up PHP, then they usually start exploring other languages.. But since they are already brainwashed from PHP use, it prevents them from seeing the value of doing thing the proper way, and might see the process as contrived. This is the most dangerous aspect of using PHP. It blocks your learning and understanding. It pulls you down and keep it there. A good example is the use of PHP arrays. It is a combination of different data structures like list, dictionaries, sets etc. But because it is a combination, you wont be able to use it as a list, or a dictionary or as a set to the fullest extent. And you will be so used to using this for every situation that you might be put off by lack of similar data structures in other languages, and blocks you from seeing the value of using the right one for a particular situation. So I request every one who is passionate about programming and wants a career in programming to keep away from the php language and community as much as possible.
- dpacmittal 12y agoInteresting that Rasmus voted a No for this.
- olemartinorg 12y agoNot really, I think. It was exactly as I expected. I once attended a mini-conference where he did a talk about PHP history. After the talk, someone asked a question about strict typing. Rasmus really hold on to the web not having types (just passing strings, as have been pointed out in other comments here). I remember him saying something like "when the web have strict types, PHP will have it too".
- Danack 12y agoThis is actually quite revealing. Some people think that PHP is just used for the same small web pages it was used for 15 years ago. Other people would like to use PHP more as a general computing language. Having optional types takes nothing away from using PHP for simple web pages, but does make it easier to right analyzably correct programs. The fact that the founder of a language doesn't want to see it grow is quite depressing.
- marrs 12y agoHe doesn't want this particular feature. Considering the amount that PHP has grown, he obviously does want it to grow.
- ZeroGravitas 12y agoSo how do you go about using this in both PHP5 and PHP7 at the same time? Do you need to run a pre-processor to strip them out of the code that runs on PHP5, while getting the benefit for testing on PHP7? Trying it naively, PHP5 thinks you want to use a class called "int". And doesn't like the : for the return value.
- nnq 12y agoWhy do we need to duplicate the effort that people (some very smart people, btw!) have put into Hack (http://hacklang.org/ http://hacklang.org/), a sane strictly typed PHP successor with many other good stuff added?! (imho, not only good, but awesome stuff, like XHP https://www.facebook.com/notes/facebook-engineering/xhp-a-new-way-to-write-php/294003943919 https://www.facebook.com/notes/facebook-engineering/xhp-a-ne... and async/await http://docs.hhvm.com/manual/en/hack.async.php http://docs.hhvm.com/manual/en/hack.async.php) And as a bonus, both HHVM.PHP and Hack and are well optimized to run at Facebook's scale... seriously, let's just leave Zend.PHP rot away in the trashcan of history and move the f on!
- marrs 12y agoWell an obvious reason is all the PHP site that have already been written, are crucial components in many businesses, and cannot be upgraded to Hack. Those sites' authors may still want access to all that good stuff. In fact, this kind of feature may make it easier to convert those applications to Hack in the future.
- nnq 12y agoYou can freely mix Hack code and PHP code on the HHVM, calling functions and classes defined in any PHP file inside you Hack app. Then you can slowly evolve the codebase to contain more and more Hack and less and less PHP. That's the huge point that nobody seems to see. But then again, considering how many other huge points PHP developers seem to miss in general, maybe it's better to just let Node.js eat the world :)
- marrs 12y agoIn that case I take it all back! Sorry, I hadn't realised HHVM was so far along.
- ChikkaChiChi 12y agoI think it is important for what Facebook has done to fork and bleed all over the edge of optimization. What needs to happen is that the best features to come out of that float up to the root language and are adopted as part of the standard. PHP the language will always rely on PHP the brand being as ubiquitous as it is. The more that can be done to improve the language, the stronger the brand and the longer it will endure.