Kao
Kao

Reputation: 2272

Typecast function parameters

I would like to check the type of a parameter matches, before I enter a the function.

function ((int) $integer, (string) $string ) { /*...*/ }

As opposed to

function ( $int, $string ) {
    $string = (string) $string;
    $int = (int) $int;
}

Is there a way to do this? I've also speculated in doing it as object

function ( Integer $int ) { /*...*/ }

By doing this I could send a functionName ( new Integer ( $int )); but I would love to not have the added syntax.

Upvotes: 11

Views: 16211

Answers (5)

Tomas Buteler
Tomas Buteler

Reputation: 4117

Starting in PHP 7 you can now use Scalar types (int, float, string, and bool) when type hinting.

function (int $int) { /*...*/ }
function (float $float) { /*...*/ }
function (string $string) { /*...*/ }
function (bool $bool) { /*...*/ }

As of OP's question, PHP only supported type hinting of objects, interfaces and the array type, but it is now possible to do what the question proposes natively.

Upvotes: 19

raina77ow
raina77ow

Reputation: 106385

You certainly can use so-called type hinting with complex types (arrays, interfaces and objects) - but not with primitives (and, to my mild surprise, with traits as well):

Type hints can not be used with scalar types such as int or string. Traits are not allowed either.

While there's a lot of proposals to add the scalar type hinting to PHP (there's even an informal patch for that), it's not that easy. I'd recommend checking out this article, as it sums up the potential pitfalls of different approaches pretty well.

P.S. BTW, it looks like PHP 5.5 might use that "check-and-cast" type hinting. Not to say I'm surprised...

Upvotes: 7

Svetoslav
Svetoslav

Reputation: 4676

http://php.net/manual/en/language.oop5.typehinting.php

You cant set such check for INT and STRING.

Upvotes: 0

pozs
pozs

Reputation: 36224

There will be scalar type-cast-like type-hint in function parameters in php 5.5, but for now, only classes, array & callable only available (as of php 5.4)

Upvotes: 0

JvdBerg
JvdBerg

Reputation: 21856

For scalars you can use the php is_int() .. is_string() functions to check.

For arrays and objects you can use type hinting in the function call.

There is a rumour that in the next version of php there will also type hinting support for scalars.

Upvotes: 0

Related Questions