46

I'm trying to make a function with declared argument types, to quickly check if they are in the right format, but when it returns a string I this error:

Catchable fatal error: Argument 2 passed to myfunction() must be an instance of string, string given, called in path_to_file on line 69 and defined in path_to_file on line 49

Example

function myfunction( array $ARRAY, string $STRING, int $INTEGER ) { 
    return "Args format correct"; 
}
myfunction(array("1",'2','3','4'), "test" , 1234);

Where is the mistake?

2
  • You can't hint of for scalar values. Commented Jan 22, 2012 at 16:58
  • 3
    Now you can, just use PHP 7.0 php.net/manual/en/… Commented Nov 3, 2015 at 15:42

9 Answers 9

62

According to the PHP5 documentation:

Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.

Since string and int are not classes, you can't "type-hint" them in your function.

As of PHP 7.0 declaring argument type as string, int, float, bool is supported.

Sign up to request clarification or add additional context in comments.

3 Comments

this answer is outdated, see php.net/manual/en/…
What if I have a class Person and I want to accept an array of Person as parameter for my function? How can I do that?
again updating the link to PHP documentation: php-legacy-docs.zend.com/manual/php5/en/functions.arguments
38

This maybe useful for anyone who see this post since the availability of PHP 7

With PHP 7, its now possible to declare types. You can refer the following link for more information.

http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

function(string $name, bool $is_admin) {
    //do something
}

3 Comments

is it always recommended to include parameter type?
What about the syntax of the return type of this function?
@AlexLacayo I think it's good practice. PHP has always been very lenient when it comes to variable type and assigment. But being too open will inevitably lead to head scratching bug one day. Return type is declared using a colon, followed by return type. For example : function foo() : int { return 0; }
6

According to PHP Manual, you can do that for array on PHP 5.1 and beyond and for string and int types on PHP 7 and beyond. Take a look:

  • Class/interface name The parameter must be an instanceof the given class or interface name. PHP 5.0.0
  • self The parameter must be an instanceof the same class as the one the method is defined on. This can only be used on class and instance methods. PHP 5.0.0
  • array The parameter must be an array. PHP 5.1.0

  • callable The parameter must be a valid callable. PHP 5.4.0
  • bool The parameter must be a boolean value. PHP 7.0.0
  • float The parameter must be a floating point number. PHP 7.0.0
  • int The parameter must be an integer. PHP 7.0.0

  • string The parameter must be a string. PHP 7.0.0

  • iterable The parameter must be either an array or an instanceof Traversable. PHP 7.1.0

2 Comments

You can use array as hint since PHP 5.1.0
Of course, you're right, I wrote it right myself after writing wrong hehe.
5

You can do something like this which has always worked for me

for string

function setData($Name=""){ }

this forces the name to be a string, it doesn't check if its a string

for numeric values

function setData($age=0){ }

this forces the age to be a number, if a string is passed, the value will be 0

for array values , there are two variation

function setData(array $data){ } 

if an array is not passed, it would throw an error

function setData($data=array()){ } 

This would pass an empty array of no value is given for $data

1 Comment

Specifying default values for arguments is an important technique but shouldn't be equated with type hinting. For example, it's not entirely true that specifying func( $x=0 ) forces the value of $x to be a number. Rather, if your function always processes the value of $x as a number throughout, then by coincidence it works out. Actually if you pass in a string that happens to be parsable as a number, then it will be processed that way. func( '5' ) would cheerfully use 5 as the integer value. A string that isn't parsable is interpreted as zero, so your 0 default works by coincidence.
1

string, int and other built-in types are not classes, in argument you specify class, of the argument. The only supported built-in type to be put there is array.

Comments

0

You cannot define type as string and int. PHP "does not know" what they are.

1 Comment

It does know the types, it just doesn’t care.
0

If you are not using PHP 7.x or need some complex argument validations (like "an array or \Traversable" because you can traverse arrays but they are primitive types and don't implement the \Traversable interface) you can use args module from Non-standard PHP library (NSPL).

use const \nspl\args\numeric;
use function \nspl\args\expects;

function sqr($x)
{
    expects(numeric, $x);
    return $x * $x;
}

sqr('hello world');

Outputs:

InvalidArgumentException: Argument 1 passed to sqr() must be numeric, string given in /path/to/example.php on line 17

Call Stack:
    0.0002     230304   1. {main}() /path/to/example.php:0
    0.0023     556800   2. sqr() /path/to/example.php:17

Comments

0

when I need use Type Hints, I do this:

<?php 
declare(strict_types=1);

1 Comment

Please add more description regarding your answer.
0

Type declared variable arguments from PHP7


<?php
function total_intervals($unit, DateInterval ...$intervals) {
    $time = 0;
    foreach ($intervals as $interval) {
        $time += $interval->$unit;
    }
    return $time;
}

$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';

// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);

https://www.php.net/manual/en/functions.arguments.php#example-164

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.