top | item 9214464

PHP7 Gains Scalar Type Hints

150 points| pbowyer | 11 years ago |wiki.php.net | reply

143 comments

order
[+] Danack|11 years ago|reply
To 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|11 years ago|reply
The 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|11 years ago|reply
> 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?

[+] ZeroCoin|11 years ago|reply
I 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.

[+] wyager|11 years ago|reply
If I cut off the limbs of a bunch of athletes and glue them together, it doesn't make a better athlete.
[+] jhall1468|11 years ago|reply
I think the part where you said "best bits" is debatable.
[+] jkoudys|11 years ago|reply
Finally! 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.

[+] pbiggar|11 years ago|reply
That's right, the PHP community _votes_ on language features.
[+] wvenable|11 years ago|reply
Since PHP has switched to community voting, the language has expanded smartly by leaps and bounds while maintaining a great degree of compatibility.
[+] TazeTSchnitzel|11 years ago|reply
Though 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"

[+] arenaninja|11 years ago|reply
Hooray! \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.

[+] smt88|11 years ago|reply
You've had a use for this ever since you started writing code. You just haven't realized it yet.
[+] tveita|11 years ago|reply
They're pretty inconsistent about it. They tend to avoid large deliberate breaks, but you still see smaller incompatibilities.

Off the top of my head, here's a case where they changed the output of a hash function between 5.3 and 5.4, breaking it for all previous users. https://bugs.php.net/bug.php?id=60221

[+] AlexMax|11 years ago|reply
> 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.

[+] awalGarg|11 years ago|reply
Yay! <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|11 years ago|reply
Same idea, except `use \Foo\Bar\Baz as SomeAlias` is already reserved for namespaces.
[+] Chintagious|11 years ago|reply
Wow, 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...

[+] TazeTSchnitzel|11 years ago|reply
> 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.

[+] MAGZine|11 years ago|reply
Sounds 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.
[+] nnq|11 years ago|reply
Why do we need to duplicate the effort that people (some very smart people, btw!) have put into Hack (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-ne... and async/await 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|11 years ago|reply
Well 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.

[+] ChikkaChiChi|11 years ago|reply
I 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.

[+] dpacmittal|11 years ago|reply
Interesting that Rasmus voted a No for this.
[+] olemartinorg|11 years ago|reply
Not 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".

[+] eduard44|11 years ago|reply
Good. Now I just need to wait for PHPStorm to support them ;)
[+] ZeroGravitas|11 years ago|reply
So 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.

[+] pbowyer|11 years ago|reply
A pre-processor for PHP is a nice idea... like all the ES6 ones for JavaScript.
[+] 1ris|11 years ago|reply
Can 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|11 years ago|reply
PHP 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
[+] Danack|11 years ago|reply
PHP 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).

[+] cwyers|11 years ago|reply
Is this compatible with what Facebook has done with Hack?
[+] spion|11 years ago|reply
I can't find it anywhere in the document - are these statically checked types or just run time checks (contracts)?
[+] TazeTSchnitzel|11 years ago|reply
Runtime (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.
[+] amyjess|11 years ago|reply
What happened to PHP6?
[+] TazeTSchnitzel|11 years ago|reply
PHP6 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.

[+] agumonkey|11 years ago|reply
It got a call from ECMAScript 4.
[+] leeoniya|11 years ago|reply
most of it was rolled into 5.4. i think some of the more contentious unicode parts were dropped.
[+] imakesnowflakes|11 years ago|reply

[deleted]

[+] aikah|11 years ago|reply
> Doesn't change anything. It is still shit.

To be fair there is no perfect language ,especially in dynamic/weakly typed ones. PHP "grew organically", was successful because at the time it came , it was easy enough for hobbyists and non programmers.

It's still the cheapest way to develop web apps and for those who like java patterns they can still upgrade to these because of its class system. While I wish Ruby or Python would be more popular, they are not as easy to use as PHP(while ironicaly it is easier to go further faster with rails for instance than bare bone PHP),they are not as cheap to deploy too.

There is a natural progression between learning HTML and then adding some server-side behavior , that wasn't met by other solutions (while java has JSP, forced OO makes it too complicated for beginners)

Nevertheless, PHP has excellent libraries , extensions that even some "hotter" languages do not have , I think when people start projects they don't just look at the language but also the ecosystem.

[+] Apofis|11 years ago|reply
Try 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.

[+] e-tron|11 years ago|reply
"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..