Reputation: 179
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
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
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
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