On 14 January 2015 at 14:00, Pavel Kouřil <pajou...@gmail.com> wrote:
>
>
> PS: Personally, I find the "scalar" typehint idea useless and cannot
> find a real use case for it. Richard, would you mind giving an
> example?
>

The point of the 'scalar' typehint comes about because we need to reject
non compatible types. Just like we do when we say array or callable.

Currently, if we want a method/function to accept a scalar, then we cannot
put any type hinting in and so we can supply an array, callable, class or
interface.

Being able to say 'scalar' would mean I can instantly inform the user that
any scalar can be used and that no type juggling will happen automatically.

For example, take ...

<?php
function sum(scalar $left, scalar $right) { return $left + $right;}
?>

Now in this example, sure the parameters will be juggled because of the +
operator.

But without the typehint, and the lack of operator overloading, you would
get an error if non-scalars are supplied in the addition, rather than in
the call. The + is fine, it is the wrong params to the function that should
be the problem. And a scalar typehint is the better place I think.

Now if we have polymorphic behaviour ...

<?php
function sum(scalar $left, scalar $right) { return $left + $right;} // Type
juggled addition
function sum(array $left, array $right) { return array_merge($left,
$right);} // Array merging
function sum(string $left, string $right) { return $left . $right;} //
String concatenation.
?>
(OK, 'sum' isn't a perfect example, but you see the point I hope).

Richard.





-- 
Richard Quadling
Twitter : @RQuadling
EE : http://e-e.com/M_248814.html
Zend : http://bit.ly/9O8vFY

Reply via email to