tags:

views:

1805

answers:

6

Often I hear people refer to PHP as a loosely typed language.

What is a loosely typed language and what are its pros and cons?

+12  A: 

Bad? No.

Some people like strong typing because it means the compiler catches errors before runtime.

Others like weak typing because it's more dynamic and flexible.

It's not an absolute attribute; it can be a strength or a weakness.

duffymo
Right. It's not bad and whoever told you it was, should be taken outside and beaten to death with a stick of wet celery. +1.
paxdiablo
Well hard is better than soft... that's why there are medicines to cure soft. There must be some sort of primeval freudian association there.
Robert Gould
"Some people like strong typing because it means the compiler catches errors before runtime." my argument to this has always been, that compile time is at the same step as runtime, so I still don't see the "problem".
Unkwntech
@Unkwntech one point in favor of the strongly typed languages is that you can run static code checking tools, and have a more integrated IDE, than with weak typed languages. Also people that come from hardware backgrounds, tend to have more aversion to weak typed systems, initially at least.
Robert Gould
Unkwntech: It means errors can be caught statically, without running the program. In compiled languages, that obviously means at compiletime, but you could feed an interpreted language through a static typechecker and see how many errors it could catch. Doesn't have to be at *compile*time.
jalf
I accepted Jalf's answer because it answers the actual question directly, but I have voted this up.
Unkwntech
I think you are confusing static/dynamic with strong/weak (though I'm not certain). Strong typing can help with compiler checks, but static typing is what's really important for a compiler.
Paul Biggar
I'm equating "strong" and "static", "weak" and "dynamic". I don't think I'm confused, although I'll agree that if you see shades of gray there that it might be confusing to read.
duffymo
duffymo: I'm not sure its correct to equate those. (When I left the comment, I was sure it was incorrect, but since then I've been researching, and am no longer sure. This especially had me thinking: http://stackoverflow.com/questions/430182/is-c-strongly-typed/430414#430414.).
Paul Biggar
Static and strong are very different, as are weak and dynamic. There are strongly-typed dynamic languages (Python), and there are weakly-typed static languages (C). The two categories are almost unrelated. You could still do static analysis on a weakly-typed static language, but you could not do it on the opposite. Loose typing is another word for weak typing, so your answer is incorrect.
musicfreak
+1  A: 

A loosly typed language is one where a variable's type doesn't need to be defined. For instance, in java you set up an integer variable like this:

int my_int = 5;

But in a loosly typed language like PHP, it's like this:

$my_int = 5;

See the difference?

Also, most loosly typed languages can handle variables being set with multiple types. For instance, a PHP array can hold both integers and strings like so:

$foo = array(5, 10, "hello", "goodbye");
$foo = "bar"; // now $foo is a string
Evan Fosmark
That's static vs dynamic typing, not strong vs weak (aka loose) typing.
musicfreak
+7  A: 

It isn't, necessarily. There are some dangerous issues with PHP's typing, specifically. The way everything gets implicitly promoted to boolean, for example, can cause a lot of security issues. If you have something like this: if ($_SESSION['username'] == "bob")...

That will evaluate to true if the value of $_SESSION['username'] is true. We expect it to be a string, and if it is, we will perform a string comparison as expected. But if it is another datatype, you end up doing weird, unexpected comparisons. If it is a boolean value, then "bob" will also get typecast to a bool, and we'll end up comparing true == true.

(I hope I got this right, been a few years since I used PHP)

But there are many weakly typed languages that people don't have a problem with. PHP just suffers from a lack of design. No one ever sat down and thought about how the language would actually work, what pitfalls or unexpected behavior the syntax would create.

A loosely, or weakly, typed language is simply one in which type constraints are not enforced. In the above example, you don't get an error no matter what types you're comparing. You can compare strings to ints, ints to bools, bools to chars, chars to functions, whatever you like, and PHP doesn't complain.

A strongly typed language assigns a fixed type to each variable, and so you have to explicitly specify when you want to convert it to another type. It enforces this type so that you get an error if you try to do something that is not valid for this type.

jalf
Isn't that what === is for in PHP?
Adam Peck
The loosely-typed comparison is still used in many other places where it's not possible to enforce strict type checking (array_unique, array_diff, etc)
too much php
@jalf I never noticed that bool == str, at least now I'll be sure to use ===
Unkwntech
Adam: Yes, but that doesn't change that == can act in a very surprising manner, and it is what a lot of people use. Simply allowing such meaningless comparisons is just asking for bugs. Also what Peter said
jalf
I think this answer is largely correct, but its expressed very badly. The first example is unclear, especially the term 'implicitly converted to boolean'. The start of the second paragraph is unclear. I initially thought you meant 'if the value can be considered true', but I think you really meant 'if the value is the run-time value true (ie $_SESSION['username'] === true_). Finally, fixing a type to each variable is *static* typing. Rather, strong typing means each *value* is a specific type. The rest of the paragraph is correct, but you'd need to rework it rather than change a few words.
Paul Biggar
@Paul Biggar: You're correct about static typing, but I think @jalf was referring to the fact that internally, PHP still has to assign a type to each variable; in the example, `"bob"`'s internal type would be ignored because of *weak* typing.
musicfreak
@Unkwntech - Using a triple equals is better practice. A second helpful safeguard to use is to reverse the order: `if ('bob' === $_SESSION['username'])...` Because if you forget and accidentally type a *single* equals, it will kindly throw a syntax error instead of making an assignment and evaluating to `true`, which can also cause problems.
keithjgrant
@musicfreak: The problem with @jalf's response it that it is, overall, kinda right. But nearly every point is marred with a subtle error.For example, (and I didn't understand this myself when I wrote my comment above), *strong* and *weak* typing are not well-defined terms, and don't have a commonly understood meaning. *Loose* doesn't either.Likewise, the internal type is not ignored, and the rules in PHP are more complex than the way he puts it.I know what he's getting at, and I just want to make sure that incorrect information is fixed.
Paul Biggar
If everyone has to use `===` 99% the time, then what's the point in the language being weakly typed in the first place? PHP's Weak typing just seems like a poor replacement for operator overloading to me.
Longpoke
+2  A: 

Loose typing means that variables can change their type without causing any errors.

// PHP - loosely typed - this is fine
$x = "hello";
$x = 3;

// Java - strongly typed - this is an error
String x = "hello";
x = 3;

It has advantages and disadvantages. The most obvious advantage is the flexibility it gives you. For example, you could write a function which returns an array of whatever if successful, and false if it failed, like the file() function.

$lines = file("myfile.txt");
if (is_array($lines)) {
    echo "hey it worked!";
} else if ($lines === false) {
    echo "it failed!";
}

The downside is that because there is so much flexibility possible with the variables, you have to do extra checks to make sure that you're working with what you think you're working with.

PHP does have a little bit of strong typing in it since PHP5: you can specify the variable type of function parameters.

function myfunction(Array $x, Foo $fu, Bar $bah) {
    // right here, we know for certain what $x, $fu and $bah are.
}

Unfortunately this only applies to objects and arrays, not primitives like floats, ints and strings.

nickf
That's static vs dynamic typing, not strong vs weak (aka loose) typing.
musicfreak
A: 

Large projects where teams work on common code base can benefit from static typed languages where type correctness is enforced at compile time. Especially where code from different folks mesh and integrate together.

I've done a lot of significant apps in Perl where typing is pretty loose (compared to Java or C#) - it's fast and very productive mode to create code with such languages. Wouldn't say such languages are "bad".

Where rapid production but relatively short lifetime of produced software is the emphasis (the nature of a lot of PHP scripting for the web), dynamic languages can be rather potent.

For software that is engineered to last years (and even decades), the software engineering centric languages of Java and C# have some benefits.

None-the-less, the static typed languages (where types are defined and enforced at compile time) can at times be awkward to use when dealing with some runtime situations of highly dynamically structured data/information. But even C# in versions 2.0 and 3.0 has added some features that help out here, like tuples and type inferred variable declarations. These features when used tend to confer some of the capability previously thought reserved for the dynamic scripting languages (Perl, PHP, Python, Ruby, Groovy, et al).

However, a Java developer can use a Map collection to pretty much implement tuple-like capability for "dynamic runtime-defined objects". Java developers might also start incorporating some Groovy to deal with these aspects of their application.

RogerV
+5  A: 

According to Chris Smith's excellent article What to Know Before Debating Type Systems:

Probably the most common way type systems are classified is "strong" or "weak." This is unfortunate, since these words have nearly no meaning at all. It is, to a limited extent, possible to compare two languages with very similar type systems, and designate one as having the stronger of those two systems. Beyond that, the words mean nothing at all.

Therefore: I give the following general definitions for strong and weak typing, at least when used as absolutes:

  • Strong typing: A type system that I like and feel comfortable with
  • Weak typing: A type system that worries me, or makes me feel uncomfortable

What about when the phrase is used in a more limited sense? Then strong typing, depending on the speaker or author, may mean anything on the spectrum from "static" to "sound," both of which are defined below.

While the "static" vs. "dynamic" distinction is pretty clear-cut, the difference between a "strongly-typed" language and a "loosely-typed" language is largely in the eye of the beholder.

Generally speaking, though, I find that most people consider the "strong" vs. "weak" typing distinction as a difference of attitudes:

  • Strong typing: "Don't let me do something that doesn't make sense!"
  • Loose typing: "Try to figure out what I meant and do that; don't bother me with details!"

It is easy to see that "loosely typed" in this sense can lead to difficult-to-diagnose bugs, which is why many people don't like the concept. On the other hand, people have very different ideas about what features "make sense" or "figure out what I meant", and so the terms aren't very rigorously defined at all.

Daniel Pryden
I love your, "difference of attitudes," idea. That's a good way to identify static/dynamic from strong/weak. A+
Andres Jaan Tack