top | item 23948114

Everything you need (and don't need) to know about PHP's type system

115 points| nawarian | 5 years ago |thephp.website

66 comments

order

osrec|5 years ago

It actually makes me really happy to see more positive comments on a thread about PHP. It is an incredible workhorse, and doesn't get the credit it deserves.

I'm often amused by developers that revile PHP, while going on to use another language, which suffers from a similar set of problems to PHP, oftentimes with poorer performance and more complex toolchains.

PHP deserves a little more love, imo.

bsdubernerd|5 years ago

I always used and use PHP because it gets the s$$$ done.

But truth be told, the hate is deserved. It never was a particularly efficient language, which might not matter that much, but it was riddled with gotchas, warts and horrible solutions to many technical and social problems.

Today PHP is faster than many alternatives, many of its warts got fixed, but I cannot brush off the fact that it's still based on a poorly-designed base and runtime library.

I'm still using PHP when it makes sense, in the same way I'm still using perl where it makes sense.

stunt|5 years ago

PHP has its special place for every developer that works on web. And it got all recent improvements thanks to all those criticisms. I think every popular language receives criticism and that's just fine.

I'm happy that the language is evolving and there is a strong ecosystem with quality libraries and developers unlike what it used to be 5 years ago.

I've been doing several languages (Scala, and Typescript. also Go recently) in last few years. But, I still follow PHP ecosystem closely and I'd definitely choose it for my next web startup. It's just 10x faster and ultimately cheaper to build web with PHP. That's why there are so many big success stories that started with PHP even in areas that you wouldn't believe. Surprisingly enough, not only web! One of Cloudflare's founders said on an interview that their back-end was written in PHP and it was used for a long time. That's one of the things that you think no one would do.

tutfbhuf|5 years ago

We often have comments like "actually php is not that bad" and then people might think let's give it another try, only to find out that they came across all over the same quirks of language (design) and runtime behavior again. I think the main problem of php is that it's so inconsistent. I would rather prefer a bad language if it would happen to be at least very consistently so.

paledot|5 years ago

> Important to notice that casting an array with numeric keys into an object is valid, but one can't dereference its value because property names may not start with numbers.

Not true, actually. The (admittedly obscure) syntax to access a property beginning with a numeral is `$obj->{0}`. Usually when this happens it's because someone was trying to be clever with JSON.

flir|5 years ago

There's another way to get a variable starting with a numeral - abusing extract(), I think.

duskwuff|5 years ago

Adding a static analyzer (like Psalm [1]) to the mixture makes PHP's types much more powerful. Psalm can use docblock annotations to attach more complex types to functions and variables, including:

* A "list" type representing a non-associative array

* Types representing specific kinds of values, like numeric-string or non-empty-array, as well as exact values as types (like true and false, or string constants).

* Typing on keys and values in arrays, e.g. array<class-string,int> for an array with class names as keys and integers as values

* Complex typing on the contents of associative arrays, e.g. array{foo:int, bar:string}

* Templated types on functions, like a function which returns an instance of a class whose name is passed in as a string:

    /**
     * @template T
     * @param T::class $class_name
     * @return T
     */
[1]: https://psalm.dev/

mhitza|5 years ago

Psalm is nice, however I would suggest PHPStan as an alternative for people that encounter a lot of friction with Psalm.

For example, in a project using doctrine I have to add a bunch of is null/@psal-mutation-free annotations. As all the methods can return null.

However, if Psalm had support for something like phantom types, maybe I could tag entities returned from the database for whom certain fields are guaranteed to have values.

chx|5 years ago

Minor nits:

1. "they all inherit from stdClass" -- this is simply not true

2. callables should've mentioned anonymous functions

3. a special typed value can't be casted to anything. -- this is not true, NULLs can be casted to anything (it becomes 0, "", array() ) and even resources can be casted to anything with dubious utility value.

4. casting should mention the intval() , strval() , doubleval() functions

5. php does not support explicit type definition in variable declaration -- PHP 7.4 however supports typed properties. https://wiki.php.net/rfc/typed_properties_v2

nawarian|5 years ago

I'll definitely edit the post adding the relevant bits you mentioned.

Two special notes:

About 1. stdClass, you're right and I don't know why I just took it for granted without even testing. My Bad.

About 3. casting special types, you're right again. I didn't phrase it properly. Casting null to other types won't yield errors and casting resources too. Their values are normally nothing we should rely on, but doesn't mean one "can't" perform such casts.

Thanks a lot for your comments, they are incredibly helpful! Cheers!

gwillz|5 years ago

This is quite complete, definitely bookmarking for reference.

I've been knee deep in PHP for the last 6 months after keeping it at arm's length for probably 10 years. It's really quite incredible how much it's improved and I think the type system is the major factor for me. It's not perfect but damn - I can get some stuff done really quick now.

gwillz|5 years ago

I'll add though; the real benefit only comes with heavy use of objects, like in Yii/Craft. If you've got keyed arrays everywhere it's still a hellhole.

jonny383|5 years ago

PHP rocks in 2020. Couple it with laravel or something and you get a solid platform to build a monolith-type web app with really fast performance.

noir_lord|5 years ago

It's gotten a lot better since I started using it ~2009 and now.

7.4 added typed properties. 8 is adding better caching, a jit and my favourite feature

    match()
https://php.watch/versions/8.0#match-expression

for all the enterprise heavy stuff I write a nicer cleaner and safer (by default) alternative to switch is going to make some code much cleaner to write and read and really that is what I care about more than almost anything else.

That it also returns a value is just the cherry on top. I am so tired of reading bad code with poor intent that has no comments and no documentation that's written in the most counter intuitive way.

bnt|5 years ago

Isn’t Laravel the worst performing framework out there right now, like even Rails looks like a viable option in terms of speed?

untog|5 years ago

I have to say I’m impressed by how far PHP has come. I haven’t written any in years (well over a decade, even) but the commitment to improving a language many have written off as a dead end is laudable.

forgotmypw17|5 years ago

While we are on the subject, does anyone know of a way of having required variable declarations in PHP, similar to the way Perl's "use strict" works?

This is one of my most common sources of bugs, and it is frustrating not having this be available, when it makes my life so much easier in Perl.

Lately I've been thinking about doing something crazy like implementing my own variable system...

notRobot|5 years ago

> Strict typing mode. In PHP the declare(strict_types = 1); directive enables strict mode. In strict mode, only a variable of exact type of the “type declaration” will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float.

https://www.brainbell.com/php/strict-type.html

aslamc|5 years ago

Is there a good reason to still use php when you can use hacklang (https://hacklang.org/) which has much stronger type system. Some would even call it php++.

simonhamp|5 years ago

A lot of what Hack introduced to the PHP community has become available in suitably forward-thinking ways to allow for a sensible amount of backwards compatibility and are opt-in.

For example, you can set strict typing on a per-file basis.

`declare(strict_types=1);`

I believe that the performance difference between the two is negligible now too. So it really just comes down to personal preference/platform legacy.

But Hack is on a different path which is potentially going to make it harder to share code between PHP and Hack.

PHP still has by far the larger community.

Given the choice today, I’d run with PHP.

captn3m0|5 years ago

Hack isn’t still commonly used outside of FB, and for the right reasons - the PHP community is much bigger. Very few projects test for Hack compatibility, and the performance gains aren’t worth it these days (they were 5 years ago, but not so much these days)

fraktl|5 years ago

Having "much stronger" type system cannot be anyone's definitive reason for deciding to go with Hacklang instead of PHP.

Type system doesn't guarantee that the programmer will utilize it properly, produce optimal code or even figure out the problem that is being solved by writing an algorithm.

You also need to pay attention to the ecosystem, problems that come with HHVM, the fact you're undoubtedly tying yourself with Facebook and what you're gaining / losing with the decision to go with a fork of PHP.

Shish2k|5 years ago

If you’re building an app to run on other people’s servers, vanilla PHP is much more widely available :(

(Sad because I use Hack in my day job and PHP for my open source projects, and find Hack way more pleasant and productive)

choma|5 years ago

Completely unrelated but, if the site owners read this: pleas, make the CSS ::selection a different color from the background, please!!

nawarian|5 years ago

Thanks for pointing this out. It annoyed me a lot as well. The whole "dark mode" css was a "better than nothing" thing, and now I'm collecting the "must fix" things. This is definitely on the list!

That said: the website is open source, feel free to submit a PR if you find time before I do :D

wolco|5 years ago

Main takeaway: strict types won't make your code faster!

It may make it slightly slower

fennecfoxen|5 years ago

The point of strict types is generally not speed, but rather, to make your code more correct.