Awkward PHP type error in function arguments

justSaid

I have defined a function like this:

   private function mediaExist(string $entry) { ...

and I'm getting this type of error:

   ... must be an instance of string, string given, called in ...

Any help ?

Elias Van Ootegem

PHP type-hints only work for classes or arrays:

function foo(array $bar, stdClass $object)
{//fine
}

But you can't type-hint primitives/scalar or resource types:

function bar(int $num, string $str)
{}

This would invoke the autoloader, which in term will attempt to find class definitions for the int and string classes, which obviously don't exist.
The rationale behind this is quite simple. PHP is a loosely typed language, and a numeric string can be turned into an int, or float, through type-juggling:

$foo = '123';
$bar = $foo*2;//foo's value is used as an int -> 123*2

type-hints were introduced to improve the OO capabilities of the language: a class/interface should be able to enforce a contract, through use of (among other things) type hinting.

If you want to ensure a given value is a string, you can use casts, or type-checking functions:

function foo($string)
{
    $sureString = (string) $string;//cast to string
    if ($sureString != $string)
    {//loose comparison, if they are not equal, the argument could not be converted to a string reliable
        throw new InvalidArgumentException(__FUNCTION__.' expects a string argument, '.get_type($string).' given');
    }
}

As far as resources are concerned (things like a file handler), it's just as easy to fix:

function foobar(/* resource hint is not allowed */ $resource)
{
    if (!is_resource($resource))
    {
        throw new InvalidArgumentException(
            sprintf(
                '%s expects a resource, %s given',
                __FUNCTION__,
                get_type($resource)
            );
        );
    }
}

In the end, the best thing to do when developing a sizable PHP project is to use doc-blocks, and a decent IDE. When you call a function/method, the IDE will use the doc-blocks to tell you what types are expected. It's the programmers job to ensure those criteria are met:

/**
 * Some documentation: what this function does, and how the arguments
 * are being used
 * @param array $data
 * @param string $key
 * @param string $errorMsg = ''
 * @return mixed
 * @throws InvalidArgumentException
 **/
function doStuff(array $data, $key, $errorMsg = '')
{
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function sendRegistrationErrorNotification()

分類Dev

How printf() function knows the type of its arguments

分類Dev

How to type a composed function with spread arguments in Typescript?

分類Dev

Variadic Templated Function with Arguments all of Same Type

分類Dev

Laravel - Type error: Too few arguments?

分類Dev

"This function takes no arguments" error when calling UDF

分類Dev

Typescript generics: infer type from the type of function arguments?

分類Dev

How to get the arguments to a php function via grep?

分類Dev

"Undefined function 'function_name' for input arguments of type 'double'."

分類Dev

How to get compile time error checking with real valued function arguments?

分類Dev

Error in regards to positional arguments in python while performing function overloading

分類Dev

Unused 'x' in function arguments, but 'x' is needed - JSLint error

分類Dev

chroot() function returning "undefined function error" in php

分類Dev

Type error related to generics depending on location of function

分類Dev

DLookup Function in Access returns Type Mismatch Error

分類Dev

Typescript throws error for return function type

分類Dev

lodash Type Error has no function findKey()

分類Dev

Arguments of function inside a function

分類Dev

Angular Component using Javascript Library function throwing Type Error: is Not a Function

分類Dev

Create variable of arguments type

分類Dev

Symfony (OrangeHRM): Error for Dot in php name function

分類Dev

Why is an overloaded function with two arguments of type double called when passing a long long?

分類Dev

Is there a way to pass a void function with any type and amount of arguments as an argument in a method and store it in a data member? (C++)

分類Dev

Shader error : incorrect number of arguments to numeric-type constructor - Unity3D

分類Dev

lua not modifying function arguments

分類Dev

Python function arguments not deepcopies

分類Dev

bash: expanding function arguments

分類Dev

Arguments in js function

分類Dev

Too few arguments in function

Related 関連記事

  1. 1

    PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function sendRegistrationErrorNotification()

  2. 2

    How printf() function knows the type of its arguments

  3. 3

    How to type a composed function with spread arguments in Typescript?

  4. 4

    Variadic Templated Function with Arguments all of Same Type

  5. 5

    Laravel - Type error: Too few arguments?

  6. 6

    "This function takes no arguments" error when calling UDF

  7. 7

    Typescript generics: infer type from the type of function arguments?

  8. 8

    How to get the arguments to a php function via grep?

  9. 9

    "Undefined function 'function_name' for input arguments of type 'double'."

  10. 10

    How to get compile time error checking with real valued function arguments?

  11. 11

    Error in regards to positional arguments in python while performing function overloading

  12. 12

    Unused 'x' in function arguments, but 'x' is needed - JSLint error

  13. 13

    chroot() function returning "undefined function error" in php

  14. 14

    Type error related to generics depending on location of function

  15. 15

    DLookup Function in Access returns Type Mismatch Error

  16. 16

    Typescript throws error for return function type

  17. 17

    lodash Type Error has no function findKey()

  18. 18

    Arguments of function inside a function

  19. 19

    Angular Component using Javascript Library function throwing Type Error: is Not a Function

  20. 20

    Create variable of arguments type

  21. 21

    Symfony (OrangeHRM): Error for Dot in php name function

  22. 22

    Why is an overloaded function with two arguments of type double called when passing a long long?

  23. 23

    Is there a way to pass a void function with any type and amount of arguments as an argument in a method and store it in a data member? (C++)

  24. 24

    Shader error : incorrect number of arguments to numeric-type constructor - Unity3D

  25. 25

    lua not modifying function arguments

  26. 26

    Python function arguments not deepcopies

  27. 27

    bash: expanding function arguments

  28. 28

    Arguments in js function

  29. 29

    Too few arguments in function

ホットタグ

アーカイブ