Necko
Necko

Reputation: 179

php indicate the real type

I would like or I will prefer indicate the real type of a parameter in a function with Php, it's possible ?

Example :

<?php
function test($param)
{
   echo $param;
}
$str = "hiiiii everyone";
test($str);
?>

Instead of put just $param in the function test; I would like put something like that

function test(string $param) // string is the type of the param, that can be int, long ect or an object which I had created.

It's possible to do that with the last version of PHP ?

Upvotes: 0

Views: 314

Answers (4)

DaveRandom
DaveRandom

Reputation: 88697

What you are looking for is Type Hinting. However, as stated in the linked manual page:

Type hints can not be used with scalar types such as int or string.

This means that no, you cannot force the argument for a function to be string. You can force it to be an instance of a specific class, something which is callable, or an array.

If you want to force an argument to be a string, do something like this:

function my_func ($mustBeAString) {
  if (!is_string($mustBeAString)) return;
  // Do stuff here
}

Upvotes: 1

Sampson
Sampson

Reputation: 268482

Type Hinting was introduced in PHP5. You can now force parameters to be of a certain type by providing that type in the parameter list itself, as your example demonstrated.

Unfortunately, scalar objects (like int, and string) are not permitted.

You can do your own checking internally to determine whether the passed object is of the proper type using methods like gettype(), is_string() (handle other types as well), or even the type operator instanceof.

Upvotes: 1

Alex Turpin
Alex Turpin

Reputation: 47776

No. PHP is a dynamically typed language; variables (and as such, parameters) don't have set types. You could try and enforce your own thing using gettype, ie:

function test($param) {
    if(gettype($param) != "string")
        throw new TypeException //or something
}

But it's a bad idea. Don't try and implement features from other languages in a language you're new to. Just try and embrace the proper way and see how it goes from there.

Upvotes: 1

Dale
Dale

Reputation: 10469

I would like to bring this to the table:

var_dump($str);

Upvotes: 0

Related Questions