Jump to content

Type hinting for int, float, bool, and string


rw57

Recommended Posts

  • 2 weeks later...

There's been talk about scalar type hinting on the PHP internals list. Not that the patch you wrote isn't cool (I did look at it), but my question is why? Warning: I'm not flaming, but I am I'm biased toward dynamic languages & duck typing. Your blog seems to suggest that we're at complete opposites. 8) I honestly would like to see one or two solid use cases for such a thing.

 

I've written a lot of strongly typed code in C++ and Java, so I naturally would hate to see rigid types in PHP. I simply don't think it belongs and I fear that code might collectively devolve into things like:

 

<?php
abstract class FooBase {
    private $value = null;
    abstract public function setIntValue(int $value);
    abstract public function setBoolValue(bool $value);
    abstract public function setFloatValue(float $value);
    abstract public function setStringValue(string $value);
    abstract public function setValueToNull();
}
?>

 

I was going to say that the code above is an exaggeration, but it's not. I work on a project that has nearly the same thing sprinkled over 400+ classes. The major difference is that scalar typing is enforced by a bunch of is_int(), is_bool(), is_float() and is_string() calls. The result is that everyone simply casted everything, but of course, inconsistently. You can't have scalar typing without adding more typecasting. They go hand in hand.

 

Some people, obviously not myself, prefer explicit type declaration (and typecasting) to inference. Considering that scalars can (and are) casted automatically... I'm still wondering why take type safety to this level? Explicit casting might make code look like the early days of C with many (void *) pointers:

 

$foo->setIntValue((int) $GLOBALS['id'], (int) $_POST['foo'], $_POST['bar'] == 'yes' ? true : false);

 

Do I have to narrow of a view?

I think it really only matters when you are developing a library for other people to use. In this case, you really want to ensure the data that is being submitted is the type of data you're looking for.

 

I'd like to be able to typehint basic types of I need to, for some reason. Instead of having:

 

<?php

//silly example
function add2nums($a, $b) {
  assert (is_int($a));
  assert (is_int($b));

  return $a+$b;
}

//better

function add2nums(int $a, int $b) {
    return $a+$b;
}
?>

 

More readable, to me at least :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.