I'm an advocate for introducing optional type hinting as I write many
assert('is_*($foo)') a day.

On Thu, Jul 2, 2009 at 9:28 AM, Stanislav Malyshev <s...@zend.com> wrote:

> And there's only two ways to do it - either make absolutely all functions
> and variables that interact with typehinted functions to be strict-typed
> (which we don't plan do) or do casts on each call to hinted function. I do
> not see how anything else could produce robust code provided that type
> mismatch is a fatal error and variables can not carry type.


In an application not all layers have to deal with arbitrary parameters,
only the layer with user input does. Do I write a (Traversable) cast before
passing an object to foreach()? No, because the object is not user input. My
application will parse POST, GET, COOKIE parameters in layer 1 and call the
underlying layer 2 with the right data type; down from the layer 2 to 4, 5,
10 layer I can use type hinting.
Type hints became part of the contract of layer N: if there is a runtime
error the problem is in layer N-1 not respecting the contract.
function generate_numbers(int $maximum)
{
    return .....
}
function presentation_layer_display_numbers($input) {
    if (isset($input['max']) and is_numeric($input['max'])) {
        foreach (generate_numbers($input['max']) as $i) {
            echo "<p>$i</p>";
        }
    } else {
         echo $formCodeWithHighlightedErrors;
    }
}
presentation_layer_display_numbers($_POST);
Validating input it's something we should already do, but the other parts of
the code can use type hinting. If I really pass a type that is not right to
generate_numbers(), it will be a very bad thing because the function will
not know how to recover; and it should not do: it's a job for the top layer.

Also, looking at the patch I think it doesn't cover the matter of inheriting
> the typehinted methods - i.e. if there's a typehinted method, could I
> override it with non-typehinted version or vice versa? What about typehinted
> interfaces?


For the Liskov Substitution Principle if B extends A you should be able to
call B as if it were A. So typehinted methods should be overriden respecting
the typehint to allow polymorphism.
interface Calculator
{
    public function sum(int $a, int $b);
}
class ScientificCalculator
{
    public function sum(int $a, int $b);
}
class BrokenCalculator
{
    public function sum(int $a, string $b); // some error is thrown
}
class AnotherBrokenCalculator
{
    public function sum(int $a, $b); // some error is thrown
}

-- 
Giorgio Sironi
Piccolo Principe & Ossigeno Scripter
http://ossigeno.sourceforge.net

Reply via email to