Hacker News new | past | comments | ask | show | jobs | submit login
Typed Properties in PHP 7.4 (stitcher.io)
205 points by brendt_gd 80 days ago | hide | past | web | favorite | 157 comments



Tons 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.


PHPStorm has excellent support for types and version 2019.2 released last week includes typed properties already: 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.


I've come to realize that PHPStorm is _the_ IDE for PHP, after having tested several IDEs (including VSCode).


This statement is pretty much true for all Jet Brains products.


For the most part, definitely. WebStorm is the only one of their IDEs I'd disagree about, particularly if you're writing TypeScript (which you probably should at least be thinking about doing). VSCode and its language server integration are great.


2019.2 fixed a lot of intellij/typescript papercuts for me, vscode still has a slight edge (it's error messages are still better) but the gap is close enough that I haven't had to boot open it in vscode to figure out what the error message means since I started using the RC.


I kept hearing this, then Google migrated to InteliJ as basis for Android Studio and I changed my mind about Eclipse (for the better).

Most shortcuts are only three keys instead of relying on both hands, files get incrementally compiled on save, just like Netbeans I can use Ant or Maven as the project format, indexing actually stops instead of being done every time application starts, my humble laptop doesn't sound like a propeller plane getting ready for take-off, Javadoc works out of the box without having to dive into settings, no more hunting for problems, easily displayed dynamically without having to trigger manual inspections, ...


at 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)


Try Psalm’s language server: https://psalm.dev/docs/running_psalm/language_server/ and let me know how it is for you - I use it on its own codebase (160k LOC) and also on Vimeo’s (much bigger)


thanks! will try it out


prohibitively expensive? I think you haven't thought this through.

Already Chairs, Desk and Rent for every engineer is more expensive than 200 USD every year. Their salary is many hundred times 200 USD. I pay more for coffee and water that they can get for free every year.

Independent devs without income can get PHPStorm at much lower rates.


can you tell me how independent devs can access PHPStorm at lower rates? I would love to stop using VSCode. 200USD might be ok for you, but over 800 reais for an IDE is not something I can pay.

Notebooks in Brazil are almost three times as expensive as abroad, internet costs are through the roof here as well as living costs...

I thought this through, I just have a harder reality than you I guess


You can get a free license if you are part of an open-source project: https://www.jetbrains.com/opensource/

And if you are an individual, the license is just 89 USD.

If you are an individual contractor, then maybe you quality for a startup discount? This also gives you 50%: https://www.jetbrains.com/phpstorm/buy/#personal?billing=yea...


I can also suggest you to approach JetBrains people if you see them in at a conference. They sponsor many PHP conferences, and open source maintainers (don't have to Linus) can request or open-source license.

They also have an Early Access Program that you try out beta releases, and they are free of cost.


I completely missed the `For individuals` tab...


>can you tell me how independent devs can access PHPStorm at lower rates?

Individual license starts at $89, and fall to $71 in the first renewal, then to $53 onwards. So I think it is not that expensive. YMMV.


you also get a perpetual license if you pay for a year upfront or 12 consecutive months of your subscription, so you can stop paying and keep using the version you paid for forever


JetBrains has a handful of ways that can significantly reduce or eliminate license fees for their products https://www.jetbrains.com/phpstorm/buy/#discounts


> Already Chairs, Desk and Rent for every engineer is more expensive than 200 USD every year.

In my part of the world it is, too. But I don't think that's the case for _every_ engineer worldwide.


Depends on which country you're from but to me $199/year is nothing for what JetBrains gives me (If you go for individual license, you start from $89 down to third year and onwards $53). In fact I pay for all products pack and am in a good discount beyond the third year, like $13/mo.


yeah, in Brazil that is quite expensive...


> at 199 USD yearly phpstorm is prohibitively expensive for small teams and independent devs

First, that $200 rate is for teams; independent devs can pay a significantly lower rate (the catch is, you have to pay it personally, not expense it or be reimbursed by an employer).

And even for teams, $200 a year is nothing. If you can afford to hire devs in a first world country (US/EU/Aus/etc), you can afford tools for them. NO employer you should possibly consider working for is going to quibble over the license fee; not when they're already paying 1000 times that in fully loaded costs in salary/rent/overheads/benefits/etc.

If you can't find $200 for a tool to help you do your job, you're not really a professional. (Again, in a 1st world country.)


Spending money doesn't make you a professional. Not being able to afford liceases, saas costs, etc is common.

Why pay $ amount per year when there are great open source products available?


- How much time (i.e. labor hours) will it take to find and vet an alternative solution Y to solution X (provided that you already know that X will solve your problem/save you time)? - How do you value your time? - What's your tolerance for community-only support vs. commercial support?

The list goes on, but gratis isn't always better just because you don't need to pull out your wallet.


You usually need to vet all editors. You download a free trial or you download an open source version. After a month the paided on stops working until you pay causing friction. The open source editor keeps working and even provides updates.

In general choosing open source saves you time with yearly licease management, licease audits and removes the risk of surprise price increases and product shutdown.

Commercial support can be invaluable and can provide more value over community support. Commercial support for a code editor is wasteful in terms of cost/value and wasteful timewise (who is calling spending time about a macro feature not working).


Because even open source products should be paid for, specially when one earns money thanks their existence.


I think you misunderstand what open source is.

They are paid for by future development and / or increased adoption.

Take the most popular open source editor (vscode). Do you think microsoft is getting value from this open source product? Why didn't they charge a yearly licease fee instead of open sourcing it? They were probably more interested in increased adoption...


My point was about random people trying to make a living out of open source, while others feel entitled not to support them, while enjoying earning money.

Not about corporations doing open source as advertising stunt.

Which is precisely why anything I produce, is either commercial or under GPL.


yes, I realised my mistake of not seeing the For individuals tab... 89 USD is a little more palatable.

The thing I do not agree is that you have to pay for tools in order to be a professional. That is quite elitist. People make careers out of free platforms like Linux so for an IDE is not asking much to have a good tool for free. The community benefits from labor put into developing a free tool.


> The thing I do not agree is that you have to pay for tools in order to be a professional.

Absolutely not! You don't have to pay, and there's tons of free tools which are top rate.

What I said is that if you're a professional, you're able to pay for the tools that are worth it. If Phpstorm is worth it (and I think it is, but many devs I respect feel otherwise), $200 is deeply affordable by Western standards.

As a professional, you should have a budget for things like software licenses, books, donations to open source projects you really like, etc., whether that comes out of your funds as a consultant, or team's budget, etc. If your employer is too stingy to cover things like Phpstorm licenses...they're not treating you like a professional.

(Again, in first world/Western countries. Budgets and pay scales are different in some places!)


> If you can't find $200 for a tool to help you do your job, you're not really a professional.

I am sorry if I misinterpreted you, but that was precisely what you said.

Elaborating, I agree with you, reinvestment is really important to improve work and product quality.


> I am sorry if I misinterpreted you, but that was precisely what you said.

If you have the money to spend on tools, but think Linux or VS Code is best, that's fine.

If OS X would be better for you, but you use Linux because you can't afford the tools you need, that's a problem.

Being able to find the money for something doesn't mean you have to spend the money. At the price point of a few hundred dollars a year or less, my concern is what's best, not what's cheapest. The company I work for will happily buy a Phpstorm license for any dev who wants one, but some are happy with VS Code, and one holdout is still using NetBeans. Nothing wrong with that!


I can't even convince IT to put an SSD or increase my RAM from 8GB to 16 on this workstation. There's a process that I tried to go through and later my boss said they spent two hours on the phone with IT but it went nowhere so I asked my boss to not waste any more time on this nonsense.

I can't imagine having to justify a subscription to IntelliJ at this workplace. At least I imagine you can bring your own license to Jetbrains on a work computer here, at least that is my understanding and I won't ask anyone lest they say I am wrong!


Other professionals go to bazaar and flea markets to get their tools at a discount, but they still have to pay for them.

Just in IT it is now fashionable to feel entitled to earn money without buying tools, then comes dual licenses, closing doors or acquisitions because devs don't pay supermarket with pull requests.


Couple interesting things about the Jetbrains licenses.

- The yearly cost is purely for updates. Meaning you could just pay one time, get updates for a year and then continue using whatever version you have. - For small teams they offer a 50% discount (less than 10 people, in business less than 5 years) - If this is perhaps an open source project you can get it for free.

I got sucked into the Jetbrains family because of just how good their PhpStorm is. Especially in regards to refactoring and debugging tools.

I only wish their Javascript tools were anywhere near as good as their Php tools.


This isn't completely correct. A few years ago JetBrains changed the license.

You get the version available when you pay, and then you get a year of updates, which you can only continue using if you renew the license.

So you can only use the version available as of the moment you pay for a license.


> I only wish their Javascript tools were anywhere near as good as their Php tools.

I guess this is partially because JavaScript is a much harder language to write good tooling for, but I'm open for other explanations.


~2-5 hours gross income per year is nothing for a good tool.


It's a little rude to assume how much people are earning. I think you might be surprised how little people earn in certain parts of the world.


200USD is 1/3 labor month for a regular dev in brazil


For people making minimum wage and programming on the side, that’s actually at least about 20 hours or more


>independent devs

Don't they fall under the cheaper individual license?


This. 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 ...


Yes, it's $89, $71 the 2nd year, and $53 every year after that.


I saw no reference to cheaper licenses in the PhpStorm website


The individual license[0] starts at 89 USD a year, and continues to decrease the longer you pay for it[1] (with a 40% discount for the 3rd consecutive year and onward, putting the final price at 53 USD).

[0]: https://www.jetbrains.com/phpstorm/buy/#personal?billing=yea...

[1]: https://sales.jetbrains.com/hc/en-gb/articles/206386064-What...


You can see Psalm's support today: https://psalm.dev/r/55e554c1d8

Psalm supports all the same checks on typed properties that it already does for properties with docblock-defined types, and will make sure all your properties are properly initialised in a class's constructor.


Is there a document that explores the backwards compatibility of these (and related) changes?

Particularly for open source software it's hard to just say "from next version well use 7.4 min" so anything that can be added and fallback gracefully on older versions is handy.



That's kind of the inverse of what I'd like to see.

Similar to browser docs what you're often interetested in is the latest things and how far back you can use them, and where they will degrade gracefully further back.

Those mostly assume you have old code that you want to make work on new versions, not that you want to write new code that takes advantage of as much new stuff as possible while still working reasonably well on old versions.

It's understandable that they would prefer that everyone just upgrade faster, so it's probably not something they want to encourage (both in documentation and in making features degrade gracefully if that requires any tradeoffs.).


So these new features are backwards compatible in that old code that has no typed properties will continue to work.

This is a minor release and PHP tends to be almost completely BC even between major release versions so it's unlikely you'll face any issues.

If you want to start writing code that uses these features in an existing library then you can branch a new version that depends on PHP 7.4, and define that as the requirement in composer. That way users with older PHP versions will pull older versions of your library.


problem is that a lot of code is written using older PHP versions, and it is not that easy to upgrade from say PHP 7.0 to 7.3. Lots of refactoring deprecations involved (if you want to keep for example debug logs without breaking backend output).

I find it hard to trust a language that changes so much between minor versions. If I am wrong please tell me where so I can stop my grief at work and finally upgrade the PHP version we use.


>it is not that easy to upgrade from say PHP 7.0 to 7.3

Is that true?


No. My employer upgraded from PHP 5.4 to 7.0 with minimal fuss (we spent about a week on the migration, testing, and deployment, and it went smoothly), and 7.0 to 7.3 is trivial in comparison.

There are a few edge cases out there of course. Maybe your code base has basically been in stasis since the early days of PHP 5.x, may not even be using composer or namespaces, relies on tons of abandoned or horribly outdated dependencies, doesn't have good test coverage, etc., and then suddenly someone gets a bee in their bonnet about PHP 7.x and wants to upgrade. That's often not going to work out very well, but that's not really a PHP 7.x (or even a PHP thing). :) If you've been maintaining the code, have tests, no ancient vulnerable libraries, using current framework versions, etc, the process is going to be easy. If you're trying a big bang upgrade straight from the medieval period, not so much!


No, definetly not true. The backwards-compatability of PHP is insanely good, so upgrading is usually super trivial.


it's so good i am not able to install phpbb on php 7.3 because they're not allowing it...


There are compatibility checkers that can analyse the code and tell you what needs to be taken care of. Fixing is not automatic but it takes a few minutes to confirm each issue and upgrade it. If you have unit tests then it's all straight forward.


everything has to be upgraded. Older version of composer doesn't work with php 7.3, cakephp must be carefully upgraded. In my tests we even got different query results.

So maybe upgrading PHP itself might not be that bad, something I can't tell you for sure, but in my experience nobody uses vanilla PHP, they all wrap it in frameworks, and those must all be carefully upgraded too.


It is if your web host doesn’t allow you to upgrade your software because they control the machine


I 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) and psalm by Vimeo (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.


Having 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).


I'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.


Agreed, better types for PHP on the backend and TypeScript on the front makes life much more pleasant.


Same here.

Using GraphQL in the PHP backend und frontend TS. The schema is exported to TS and thus everything is fully types. A blessing.


I do agree, after 20 years.


I 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


Type 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.


Although some devs (and style guides) do tend to resist inference in favor of verbosity (C#). Subjectively, I love inference (like in F# or Crystal). I'm not sure if an objective winner exists for best strategy, or how to even measure that.


It is certainly subjective, but i am one of those developers who dislike inference in languages where it has them and prefer explicit typing out types - in fact i also go as far as to avoid type aliases (e.g. i prefer something like "const std::vector<some_template<some_foo>>" to "a_foo_vector" typedef for the former).

The reason is that i want to know "on site" what exactly is going on when reading and debugging code, especially outside a "smart" IDE, like when diffing changes via the command line, a web-based VCS frontend or some code review tool - especially since these tend to not show the entire code, meaning i need to switch back and forth. But even with an IDE that can show me the inferred types, it is almost always (while i say "almost always" i really mean "always" since i haven't seen any other, but there might be some IDE i haven't tried) done through some popup under the mouse cursor, meaning it is transient and slow.

For similar reasons i dislike features like operator overloading, placing non-self-initializing logic in constructors (and the equivalent in destructors), properties for anything that involves complex calculations (unless the language uses special syntax for properties that make them stand out when used) especially for getters, i prefer to use names that hint to what the code does (e.g. i'd use something like "get_foo" only if it doesn't do any calculations and give you a precomputed or cached "foo", otherwise i'd use an "action" verb like "calc_foo" or "find_foo" or whatever to hint that there is some calculation going on and isn't just a dumb getter), i avoid exceptions as they create hidden exit points for functions (and if the IDE/editor allows, i use a more visible - like bold red - font for "return" or the language equivalent so that explicit exit points are obvious), etc.

Yeah, these make code more verbose and you need to type more, but IMO the negatives are grossly overwhined against and while the positives way too overlooked.


> who dislike inference in languages where it has them and prefer explicit typing out types

So you prefer

    std::vector<some_template<some_foo>> foo = new std::vector<some_template<some_foo>>();
Rather than replace the first one with var / let / auto / whatever your language does? Why? The type is already there.


In terms of "liking" it, no, in that very specific case where the type is repeated and very long, i do not like it and i think "auto" (or var or let or whatever) looks better. However in the interest of consistency (and to a lesser extent, avoiding 'slippery slopes') i'd rather type that than use auto.

And even then that this is only in the very specific case you showed, where the type is too long, it is repeated and the constructor parameters - if any - are visually dwarfed by the duplicated type.

In practice these aren't as common as other uses of types like loop iterators for member/obtained collections (where the use of 'auto' makes it impossible to know the collection type unless you check the collection declaration) or local variables you assign to the result of some function (the return type of which again you need to check the function declaration to see) and - at least in C++ - you rarely need to do "very_long_foo* bar = new very_long_foo" as a stack allocated "very_long_foo bar" is enough (so no need to double type the type).


Maybe you're getting mixed up with Java, but that example type is wrong, since you used `new`, the vector was allocated in the heap and the appropriate type is a pointer type: `vector<T>*`.

What's more, that's a highly unusual example. Rarely would you need to heap allocate a vector. In the case of stack allocation the syntax would be `vector<T> myVec` which is as succinct as possible.


Personally I think that just makes code harder to read, and more difficult to refactor. You get benefits from leaving things inferred in some places when refactoring, preventing you from having to change a bunch of additional signatures just because you made a single change.

And the language you use is probably using aliases too in it's stdlib, so why hate on aliases? They are a great way to abstract away the details.

The boundary I prefer is to explicitly type function signatures, and leave everything else (or as much of it as I can) inferred.


TBH i only have statically typed languages in mind (like C++ and Free Pascal), so i'm not sure how it'd work in a dynamically typed language with type annotations, but to refactor i'd just... change the type and then work through the compiler errors to find the places that need their type updated. Some IDEs also provide you with tools to find all those uses and even can do the refactor themselves.

Your refactor will contain more lines of code since it'll need to also contain the updated use sites, but i do not see that as a problem at all - and even if it is one, it is only a short term small problem that is certainly not as important as having the code more obvious and readable in the long term (assuming of course you feel the same about readability as i do - after all as i wrote in my message above it is a subjective issue :-P).


> dynamically typed language with type annotations

I'm talking about statically typed languages also, just ones with inference. Haskell, Rust, Ocaml, F#, Go, etc, and increasingly languages like C# and Java are adding more and more inference.

Your response makes me think you don't really get what type inference is.


This also depends on what tool you use for development and the size of the project of course. If you are coding for a large project on a rich IDE, inference is not a bad experience because Your IDE is going to give you enough hint.


Interestingly, the positive documentation effect of types is the one that has actual empirical support.


I never said so.


Type inference is going forwards not backwards. Languages with "modern" type systems (Haskell, Ocaml, Rust, Swift, etc) have had inference from the start and it doesn't compromise type safety. There's a big difference between dynamically typed and type inferred. Haskell, for instance, was designed to have globally decideable inference (you don't have to write any type signatures if you don't want to), while still being completely type safe. Type inference is a wonderful thing, and I'm glad 'maintstream' languages are getting it. Albeit 30 years later...


I don't think the parent disagrees. Type inference is great for just about everything except dependant types which are all kinds of undecidable unless you help the compiler.


Could have been a lot sooner if the languages that first implemented type inference also focused on the more pragmatic aspects of programming. 'Type inference' is a small consolation if the tooling and ecosystem are impoverished and you can't find affordable developers. :)


PHP 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!


Haven'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.


I 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.


Oh, 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.


Java adding type inference is similar to PHP which has initially been dynamically typed adding static type features in a sense that both are trying to improve their type system gradually by adding more features.

The tooling around has also improved so they can do it now.

I like the idea of language to support more type features because there is no one ultimate type of solution for everything and in every situation.

Moreover, these are all safe changes. There is less possibility for developers to abuse these features compared to what they can do with implicit conversion, for instance.


> All in all in 20 years we'll all be writing ml ?

If everything goes well, yes. Everything is moving towards static typing with local inference.


I've been saying for a while that the best PHP code you can write today is basically Java that you were writing 10 years ago.

The trade-off between Java 7 and PHP 7.x is that Java has generics, but PHP's treatment of nullable variables is better/safer.


Type inference isn't "going backwards."


Don't interpret it as a negative.


I'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...


If 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.


Yes 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.


I’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.


The types being enforced at runtime can be seen as a last resort. It means static checkers can actually rely on the types being accurate as code which breaks the type contract won't run.


"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-382...


Slowly PHP is converging to what Java has been like 15 years ago.


What's really crazy to think about is how much flak Java took for YEARS upon YEARS from a rather non-trivial number of developers, managers, and media. It was ruthless at times. Looking back, it was pathetic. Now, all of a sudden, look at where we are. We're seeing all these not-Java languages looking more and more like Java, and conversely Java starting to impersonate the not-Javas. Weird. You have to give the team behind Java credit for pushing forward in spite of this. There's a real lesson to be learned here.


I don't understand why people say PHP is like Java. There's very little in common between the two. Because PHP has types? Lots of languages have types.

Why in the world are people comparing PHP and Java?


I think it's mostly because of PHP frameworks. From my experience with PHP (and, admittedly, not very much experience with Java), I got the impression that a lot of the PHP Framework developers read all the "state-of-the-art" Java literature on how you should build software and then they implemented that in PHP.

They just ignored the fact that Java is compiled which makes all the layers of abstraction less of an issue whereas PHP is interpreted at runtime* hence why there are few high traffic websites on PHP that don't have at least four layers of caching.

* Yes, I know this is getting better with every version, opcache getting a lot of attention in the last few minor releases and all that, but there is only so much optimization you can do with dozens and dozens of layers of factories and services. My guess is that it does a LOT more for "simple" software like WordPress and less for, say, Symfony based projects.


Except PHP already has some of the nicer features of Scala (like traits) and is more flexible (you can write Java-like code, but don't have to).


True.

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.


We'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? :-?


How is Javascript moving towards Typescript?


I don't know either.

TS was influenced mainly by C# at the start, then from FlowType and currently it's mainly influenced by ECMAScript.

So to me it feels like the other way around.


How is Python non-Algol?


How is Python Algol-based or inspired? I've never seen anyone describing as such, did Guido ever say it was?


https://web.archive.org/web/20070501105422/http://www.amk.ca...

It's in the Algol family, mostly indirectly through ABC, Modula-2 and 3, C, ...

Per the interview, string slicing actually came directly from Algol-68 (and Icon).


plpgsql and similar?


SQL you mean? True, but that's more of a DSL. In the same vein you'd have HTML, CSS, but I was talking about general purpose programming languages.



> TS feels very C# like.

Probably because they were created by the same person!


And both supported by the same company!


It somewhat ends up in a best of both world scenario though. Java 15 years ago (in my opinion) was so strict and rigid and abstract interface jokes were writing themselves in real life. PHP was in a fairly dark (though very lively) place as well.

Here we get a pretty good deal, I guess time matters.


Imo 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.


What's the difference between static typing with an Any type and optional typing?


An "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 ;).


That's very clear and interesting. Thanks :)


I 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.


The 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.


Just 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.


I 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.


Yes, 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.


"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?


Ideally you'd get a compile error, but there is no compiler in PHP. Run time is the only time PHP can tell you there's a problem.


Generics will come in a major release. So probably in 8 along with the JIT compiler


I'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!


Although isset() still returns false for null ;)


Which 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.


It's also great at hiding bugs where you mistyped the variable name passed to isset(). ;)


> 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!


You 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.


Certainly prettier than using call_user_func($foo->bar), so that's something.


even 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)();


It'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.


I guess it's a little less known but you also have to use the same technique to immediately invoke a method on a constructed object, eg.

    $response = (new Response())->handle ();
So it's not completely alien in PHP.


That's true, and probably depends on the code base.

I don't know how these patterns develop - it's very common in JS, but somewhat rare in PHP. Maybe it has to do with the average level of the programmer in each? Or jQuery's noConflict() helped it along with everybody starting with (function($) {})(jQuery), thus integrating IIFE into their active repertoire.

I don't remember (and haven't found in quickly searching) PSR saying anything about that, but that could explain a difference in usage, too.


Most PHP codebases simply don't have much use for IIFE's. A well-maintained project will be neatly organized into namespaces and classes, and undefined variables don't automatically become global. Meanwhile, PSR-1 says that a file that defines classes and/or functions should not have any side effect. So you don't have to worry about accidentally interacting with other scopes.

Anonymous functions and classes are being used more and more, but PHP isn't fundamentally event-driven like JS so there's less need to hand them out like candy and nest them several levels deep. Most of the closures I do use on a daily basis are callback functions to things like array_filter() and preg_replace_callback(), not event handlers like every jQuery code ever written.


I think it's well known by most developers using PHP. You can do the same to call a function on a newly created object.


You can also use Closure::bind / Closure::bindTo - see https://www.php.net/manual/en/closure.bind.php

<?php trait MetaTrait {

    private $methods = array();

    public function addMethod($methodName, $methodCallable)
    {
        if (!is_callable($methodCallable)) {
            throw new InvalidArgumentException('Second param must be callable');
        }
        $this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
    }

    public function __call($methodName, array $args)
    {
        if (isset($this->methods[$methodName])) {
            return call_user_func_array($this->methods[$methodName], $args);
        }

        throw RunTimeException('There is no method with the given name to call');
    }
} ?>

test.php <?php require 'MetaTrait.php';

class HackThursday { use MetaTrait;

    private $dayOfWeek = 'Thursday';
}

$test = new HackThursday(); $test->addMethod('when', function () { return $this->dayOfWeek; });

echo $test->when();


They're not nonfunctional:

  ($foo->bar)();
Methods and properties are (perhaps regrettably) separate namespaces in PHP.


I'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.


I 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.


Reading a CSV without knowing the types of the contents inside is kinda painful without optional typing (or no typing). It's a fair representation of the operations you'll perform while prototyping a thing.


Being 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.


Being able to be fuzzy at the boundaries of your program (e.g., consuming APIs or files) is a lot faster than rigorously defining your types for data un/marshalling.

Your chickens will eventually come home to roost, but the short-term productivity gains are quite pleasant.


If you really want to understand please find out why so many people prefer dynamically typed languages. Maybe start using one yourself...


And 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)


I went back and forth between typed and untyped languages. The sheer drudgery of typing out and visually filtering out while you read the obvious type information is what makes typed language feel way less fun for me. When you cut things out move them around, delete them, retype them, throw everything away again and start over... I'd never choose Java for initial implementation of anything.

I'm not sure why other people like dynamic languages but there must be some advantages.


Is most of the PHP ecosystem moving to static typing? Libraries, ORM, etc. When you're dealing with database objects, is everything a string?


This still isn't static typing, php type annotations are enforced at runtime.


[flagged]


What makes you lol?


For 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.


At 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.


C++ 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.


And 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.


Apart from apparent ignorance and knee-jerk dismissal?




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: