Tag: programming languages

Towards a consistent PHP type checking system

For most of its life, PHP has been a “weakly” typed language: values can freely shift from one state to another, and mould themselves to what an operation requires; or, in the case of objects, largely duck-typed: you don’t need a formal contract to call a method. There is, however, a trend in the language to adopt stronger typing constraints, first in function parameters, and now elsewhere in the language. As with so much in PHP, this is being done piecemeal, and without a clear road map. This is partly deliberate: a gentle introduction of optional features is less disruptive; but it is dangerous: compromises made now will shape the language for years to come.

I think it is time to grasp the nettle and say that there is a definite policy of introducing a new typing model to PHP, and a roadmap of what that means for the language. The implementation may still be incremental, but each change will be a step in a consistent direction. This post is my musings on what such a model might look like.

Continue reading

The Case for a better Switch

The C-style switch-case construct – used in various programming languages, including PHP – is a curious beast. Most commonly used as a streamlined form of if-elseif-else, it actually has more in common with the oldest of control statements, the goto, since control jumps to the first match and carries on until you tell it to stop.

Firstly, am I the only person in the world who thinks that the break should be indented to the same level as the case, not the level of the commands between? If you are using it as a series of separate elseif blocks, then surely the two form a matching pair, with the code block “enclosed” within them. Of course, you can generally break early inside the code, just like you can return early from a function, which is hard to make stand out – but that’s just an argument not to do it too often!

And, of course, the fact that another case comes along does not mean that the code won’t carry on. Which brings me neatly to my next thought: is there any language that insists you declare when you’re falling through to the next case – and if not, why not? What if every time you put a case, you had to end it with either a break or a continue? It seems to me it would prevent a lot of bugs caused by cases inadvertently falling through and running completely the wrong code. And if overloading an existing term like continue is too confusing, lets just have a fallthrough – anyone got a case against? [No pun intended; probably…]