Data Types - PHP Vs. Ruby

In conversation with a fellow PHP person now doing Perl, he asked… how does Ruby do types?? And I thought I knew how to answer him, but then when I opened my mouth I found I didn't have the words.

PHP is not a strongly typed language. You can assign $foo an integer, print it (even though it does not contain a string), assign an array and so on. PHP doesn't care.

However, if you want to be certain of the type in a variable there are a few functions to help you out.

settype($var, [type]);

example, to make sure these types

settype($foo, "bool"); // also could use "boolean"
settype($bar, "int");

I sometimes use them on form variables, which usually come in as strings and I want to make sure they are bool or int to help avoid any tainting, and having it in that type helps me check the range of the value etc.

You can also use typing casting

$foo = (bool) $foo;
$bar = (int) $bar;

Sometimes I used that when I am doing an expression, I just tag it with the type so I'm sure of what the outcome will be.

To see the 8 other primitive types in php Introduction to PHP Types

To see how different types evaluate, see the Blue Shoes - PHP Cheat Sheet" which is basically a nicer version of PHP.net Type Comparisons

Similarity you can use the gettype function, to return a string containing the type

$varType = gettype($foo); // returns "boolean"

However its slow according to the docs and the "is_" functions are given as an alternative:

is_bool($foo);
is_int($bar);

You can find the rest at http://us2.php.net/gettype

For a practial example, I used the following when displaying a new item:

$news_id = $_GET['news_id'];
settype($news_id, "int");

I don't know if this would be a sanctioned method by Chris Shiflet for preventing injection attacks…but, to me it seem to work.
Corrections? let me know :)

Next post, I'll talk about Ruby types.

Ahh yes, dynamically typed.

Ahh yes, dynamically typed. Thats kinda what I was thinking. Thanks for the clarification :)

You could always do

You could always do something like this:


class Array
  def key
    return self[0]
  end

  def value
    return self[1]
  end
end


users.sort.each do |user_hash|
  puts "user #{user_hash.key} has data #{user_hash.value}"
end

Or, alternatively, you could come up with a creative way of overriding the Hash#sort method.