29 ms·
Typed Properties in PHP 7.4
- knocte 7y agolol
- Ayesh 7y agoWhat makes you lol?
- dfcmt 7y agoFor me is the fact that PHP is starting to get more useful than Python. That coupled with the fact that it's faster (which doesn't take much, granted) is going to make me think some things over.
- nkozyra 7y agoAt this point it's faster than most interpreted languages for most things, but speed at that level is rarely something people are pining for. PHP still carries its legacy cruft around but if you can ignore that it's a useful language. As is often pointed out the real issue is all the PHP 5.4 and older code just hanging around and the desire to be backwards compatible in the hopes maintainers will upgrade PHP seems ... optimistic.
- dfcmt 7y agoC++ is also full of cruft. But you can use a subset of it and it becomes very good. Also this new mantra of "speed doesn't matter" is what brought us to Windows 10, Electron, etc. No thanks. I'm taking a stand against slow software.
- nkozyra 7y agoAnd people complain as much about C++ as they do about PHP. The emerging languages have put conservative, thoughtful design at the forefront, in great part due to these frustrations.
- coldtea 7y agoApart from apparent ignorance and knee-jerk dismissal?
- agumonkey 7y agoI find the timing odd [0] that php since v5 ressembles more and more Java very explicit type system, while Java is going backward to more implicit and infered. All in all in 20 years we'll all be writing ml ? [0] technological waves diffuse differently across cultures
- Ayesh 7y agoPHP gained a lot of good feedback from scalar typing in version 7.0, and a lot of improvements are towards more OOP. I think it's a brilliant move because it's still backwards compatible with PHP 5, and even sometimes with PHP 4!
- Piskvorrr 7y agoHaven't seen PHP4 code in a decade (and even then, it was a desperate last stand of an Anfient Monftrofity), and I'm immensely glad I didn't.
- Ayesh 7y agoI still have one client with a 2010 code base. Tools like PHPComptibity and IDE scans can easily batch-fix most of them, but some PHP 4 code never needed any changes.
- Piskvorrr 7y agoOh, it runs, all right. But it's rarely well done (pardon the pun): still fit for a computer, but harder for a human to read and understand.
- jillesvangurp 7y agoType inference does not compromise on static typing. It simply makes it less verbose. IMHO type inference has removed a lot of the arguments against statically compiled languages. Which is why things like Typescript are becoming popular. Even Python has type annotations now.
- RutZap 7y agoI'm really looking forward to this. After 10 years of programming in PHP and maintaining loads of legacy projects I've come to greatly appreciate explicit definitions and strong typing. IMHO being explicit always increases maintainability.
- noir_lord 7y agoAgreed, better types for PHP on the backend and TypeScript on the front makes life much more pleasant.
- some_developer 7y agoSame here. Using GraphQL in the PHP backend und frontend TS. The schema is exported to TS and thus everything is fully types. A blessing.
- GrumpyNl 7y agoI do agree, after 20 years.
- namelosw 7y agoImo optional typing like this is the best trade-off for now. Usually, statically typed languages is not expressive. There are a lot of abstractions are hard to express in statically typed languages. Even in Haskell. With optional typing, you can express usual ideas with types, and cheat with 'any' when not applicable. Another thing is the language itself can possibly execute without compile or even type check. Making developing feedback cycle much smoother when running tests or just save and refresh.
- 6gvONxR4sf7o 7y agoWhat's the difference between static typing with an Any type and optional typing?
- jesseschalken 7y agoAn "Any type" is optional typing if you don't need to downcast it in order to use it, like the "any" type in TypeScript and Flow. If the "Any" type is just a top type but you have to downcast it to use it, like in Kotlin, then it's not considered optional typing, since you still have to talk about types ;).
- 6gvONxR4sf7o 7y agoThat's very clear and interesting. Thanks :)
- mooreds 7y agoTons and tons of the web runs on PHP. It is a super easy language to learn and be effective in quickly. Especially if you are talking about open source content management systems, PHP is dominant. Anything that improves overall code quality of this language should be welcomed with open arms. Types, especially if they are backward compatible (as these are) will do so. I'd be interested in what kind of automated or ide support will be available, but I suppose that won't be known until this is released later this year.
- beberlei 7y agoPHPStorm has excellent support for types and version 2019.2 released last week includes typed properties already: https://www.jetbrains.com/phpstorm/whatsnew/ https://www.jetbrains.com/phpstorm/whatsnew/ Other editors (VSCode for example) can hook into Psalm or Phans Language Server to get type information from these static analyzers. Typing support in PHP Ides is usually excellent.
- gchamonlive 7y agoat 199 USD yearly phpstorm is prohibitively expensive for small teams and independent devs I don't know the state of the language server for newer php versions, but intellisense for vscode is too taxing on the CPU for relatively large projects (20k+ lines of code)
- antisemiotic 7y ago>independent devs Don't they fall under the cheaper individual license?
- tenken 7y agoThis. I use an EDU license for work and buy a personal license for home use, a personal license starts at $83 first year .. I'm on my fifth or so year so it's only $53 yearly ...
- gchamonlive 7y ago
- felixfbecker 7y agoI'm pretty excited about the new "uninitialized" state. Back in my PHP days I also had the phase of writing my own framework and ORM, and it annoyed me that I couldn't distinguish between "not loaded" and database null. This seems like it would make the "not loaded" state possible!
- jesseschalken 7y agoAlthough isset() still returns false for null ;)
- wwweston 7y agoWhich is a little weird, but cases where you'd want `isset` to treat variables intentionally set to null the same as variables that are entirely undeclared are considerably more frequent (just ran into one yesterday!) than cases where you'd need to carefully distinguish them.
- jesseschalken 7y agoIt's also great at hiding bugs where you mistyped the variable name passed to isset(). ;)
- naranha 7y agoI'm still not so convinced by PHP's runtime type checking system. It adds a little overhead, I guess that's not such a big problem, but it adds also new classes of runtime exceptions that can only be caught using tests, or with a good static analyzer. Especially if you now upgrade your application to 7.4 you can only do it with confidence when you have 100% test coverage. If a static analyzer can detect these mistakes, why even add runtime checks for it? Think TypeScript/Javascript, after the compilation is done, most type checks are removed for performance reasons. Or perhaps there is something I don't see...
- beberlei 7y agoIf you upgrade your application to 7.4, all the code doesn't have typed properties. Only when you then add them after the upgrade you should have tests for that or a static analyzer that tells you the changes you make are correct.
- naranha 7y agoYes that's true - it's a backwards compatible change. Still, static analysis is necessary when you upgrade dependencies and for your own code. For example for seeing whether adding a type to a property breaks code somewhere else. Discovering type errors at runtime is often too late. Luckily there are good static analyzers for PHP.
- donatj 7y agoI’m not sure about the properties but on method parameters at least, they will cast, e.g. if you give foo(int $bar) the string “10” it will be cast to 10. It will runtime error only if it cannot “safely” cast the value. I’m not 100% that it is a wonderful behavior, and a lot of people turn it off (which can be done on a per file declaration of strict) but for us it’s genuinely helped eliminate an entire class of error where a runaway type error would result in a really whacky value way down the line, even occasionally ending up with that stored in the database for some calculation. The kind of thing we still end up with in JavaScript to this day.
- TazeTSchnitzel 7y ago
- brendt_gd 7y agoI think that the biggest win with this feature, is not that PHP will do more runtime type checks, but that the syntax is valid. The past years we've seen several static analysers become more and more popular in the PHP community. Tools like phpstan (https://github.com/phpstan/phpstan https://github.com/phpstan/phpstan) and psalm by Vimeo (https://github.com/vimeo/psalm https://github.com/vimeo/psalm). Allowing this syntax is a great way to write cleaner code that can be statically analysed, which is far more superior than the runtime type checker.
- TazeTSchnitzel 7y agoHaving them checked at runtime is still important (I say this as someone who was involved in scalar types getting declarations finally), because it means that the types can't end up inaccurate without being noticed, weak typing can be supported with certainty (you always get the type you ask for), and as a bonus the runtime can perform optimisations (elided type checks).
- scotty79 7y agoI'm happy to see more languages with optional typing. Prototyping stuff without bothering with types and adding them when your code matures to root out some bugs and make it more futureproof seems to me like the best of both worlds.
- superfist 7y agoI will never undestand this argument. Bothering with types? How? In most cases you will need int, double or string - how this is difficult? It is more difficult to figure out types you heve to deal with if language doesn't provide such information. If by prototyping you mean Hello World like apps then ok, but anything more complex without types becomes mess very quickly and prototyping speed have to decrease.
- sdoering 7y agoBeing a data analyst using Python, I would say that for an one of exploratory analysis in jupyter I can do without type hints. As soon as I switch to an IDE or even go over some complexity threshold, I am all in for type hints. Or if I need to reuse the notebook. Then type hints are a blessing.
- deleted 7y ago[deleted]
- scotty79 7y agoIf you really want to understand please find out why so many people prefer dynamically typed languages. Maybe start using one yourself...
- Risord 7y agoAnd what if you are used dynamically typed language for years and still cannot understand why anyone would choose on if can chose freely? Seriously I have noticed that static vs dynammic preference is quite sustainable thing for people. Even if you are have used lot of both most people prefer the one they are used when they 'got it' during their programming learning path. I don't really understand that CSV example what's the problem but one concrete challenge I have noticed with static types is when you want do mutation which effectively change the type. Instead of setting just new property you have to potentially do dummy copy (including type) or some additional hashmap by id for this additional data. (btw I am not your down voter)
- kijin 7y ago> All types are allowed, except void and callable Urgh. It baffles me that 10 years after their introduction, anonymous functions (closures) remain useless when assigned to instance properties. class Foo { public $var; } $foo = new Foo(); $foo->bar = function() { echo "Hello World\n"; }; $foo->bar(); Uncaught Error: Call to undefined method Foo::bar() Callables work perfectly fine when assigned to standalone variables or array members: e.g. $foo[0](); But they become nonfunctional when assigned to instance properties. I understand that using closures as instance properties would make them hard to distinguish from methods, but blurring that distinction is just so damn useful in JavaScript!
- adamwathan 7y agoYou can invoke an anonymous function assigned to an instance property using `__invoke()`: class Foo { public $var; } $foo = new Foo(); $foo->bar = function() { echo "Hello World\n"; }; $foo->bar->__invoke(); Not pretty but that's how I've always done it.
- luckylion 7y agoCertainly prettier than using call_user_func($foo->bar), so that's something.
- rossriley 7y agoeven better, you can surround the class and method reference in parentheses and call normally. Example: $c = new stdClass; $c->test = function() { return 'hello world'; }; echo ($c->test)();
- luckylion 7y agoIt's less obvious though, you need to know what's happening and why. Likely not a problem for somebody writing a lot of JS, but I rarely see similar constructs in PHP code.
- tasubotadas 7y agoSlowly PHP is converging to what Java has been like 15 years ago.
- k__ 7y agoTrue. I'm also seeing that with JavaScript and TypeScript. TS feels very C# like. Luckily there seem to be counter movements with languages like Reason, ClojureScript and PureScript.
- muglug 7y ago> TS feels very C# like. Probably because they were created by the same person!
- deleted 7y ago[deleted]
- benbristow 7y agoAnd both supported by the same company!
- oblio 7y agoWe're basically getting a huge Algol mono-language. C is not really moving, but C++ is also converging towards this Java++ language. Java itself is finally moving. C# is a bit ahead of the curve, because it can follow the trail blazed by F#. PHP started moving towards Java back from when PHP5 was introduced. Javascript is moving towards Typescript which is following C#'s lead. Python is kind of the only non-Algol mainstream hold out. Did I miss any of the big enterprise languages? :-?
- babyloneleven 7y agoHow is Python non-Algol?
- oblio 7y ago
- donatj 7y agoI love the idea, but the implementation is IMHO poor. It doesn’t require non-nullables to be defined by the end of the constructor. Instead it moreorless adds a new type of NULL to the language (always a mistake) which causes parameters to throw runtime errors on call if they were not defined. This adds up to essentially making everything nullable, regardless of if the type is defined as nullable, and adding an entire class of runtime errors that could have been avoided.
- TazeTSchnitzel 7y agoThe idea behind it was to avoid having every typed property be nullable. It's important to note that the undefined state of a property cannot be read as a value, and so can't be propagated anywhere.
- donatj 7y agoJust do it like TypeScript though where they just have to be defined by the end of the constructor or be nullable/have a default. A new state was not necessary.
- TazeTSchnitzel 7y agoI think the problem is that doesn't work for cases where you have a minimal constructor and do the rest in a static method which wraps it, or where you construct the class while skipping the constructor (and probably some other cases). PHP allows more flexibility here than other languages, and these sorts of cases are not uncommon. Mocking libraries and databases interfaces do the latter, and using the former to simulate multiple constructors is a common pattern.
- fetbaffe 7y agoYes, a new state is unfortunate, however a lot of PHP code uses classes as pure data classes without any constructor & with only public properties, i.e the class functions more like a struct where you assign property values from outside the object instance. Requiring a constructor would remove a perfectly valid code pattern that is in use today.
- c487bd62 7y agoIs most of the PHP ecosystem moving to static typing? Libraries, ORM, etc. When you're dealing with database objects, is everything a string?
- joshlemer 7y agoThis still isn't static typing, php type annotations are enforced at runtime.
- ppeetteerr 7y ago"Because uninitialized state is checked when accessing a property, you're able to create an object with an uninitialized property, even though its type is non-nullable." This is going to result in a new series of run-time-only bugs that PHP is famous for. I love the language but it's 2019 and we should be past this. Also, where are the generics?
- wwweston 7y ago"But, before you pounce on this feature and start porting all your existing model classes to use this feature, you should definitely read this." https://dev.to/mindplay/php-typed-properties-think-twice-3824 https://dev.to/mindplay/php-typed-properties-think-twice-382...