How to resolve "must be an instance of string, string given" prior to PHP 7?

122,009

Solution 1

Prior to PHP 7 type hinting can only be used to force the types of objects and arrays. Scalar types are not type-hintable. In this case an object of the class string is expected, but you're giving it a (scalar) string. The error message may be funny, but it's not supposed to work to begin with. Given the dynamic typing system, this actually makes some sort of perverted sense.

You can only manually "type hint" scalar types:

function foo($string) {
    if (!is_string($string)) {
        trigger_error('No, you fool!');
        return;
    }
    ...
}

Solution 2

From PHP's manual:

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.

So you have it. The error message is not really helpful, I give you that though.

** 2017 Edit **

PHP7 introduced more function data type declarations, and the aforementioned link has been moved to Function arguments : Type declarations. From that page :

Valid types

  • Class/interface name : The parameter must be an instanceof the given class or interface name. (since 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. (since PHP 5.0.0)
  • array : The parameter must be an array. (since PHP 5.1.0)
  • callable : The parameter must be a valid callable. (since PHP 5.4.0)
  • bool : The parameter must be a boolean value. (since PHP 7.0.0)
  • float : The parameter must be a floating point number. (since PHP 7.0.0)
  • int : The parameter must be an integer. (since PHP 7.0.0)
  • string : The parameter must be a string. (since PHP 7.0.0)
  • iterable : The parameter must be either an array or an instanceof Traversable. (since PHP 7.1.0)

Warning

Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:

<?php
  function test(boolean $param) {}
  test(true);
?>

The above example will output:

 Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1

The last warning is actually significant to understand the error "Argument must of type string, string given"; since mostly only class/interface names are allowed as argument type, PHP tries to locate a class name "string", but can't find any because it is a primitive type, thus fail with this awkward error.

Solution 3

PHP allows "hinting" where you supply a class to specify an object. According to the PHP manual, "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." The error is confusing because of your choice of "string" - put "myClass" in its place and the error will read differently: "Argument 1 passed to phpwtf() must be an instance of myClass, string given"

Solution 4

As others have already said, type hinting currently only works for object types. But I think the particular error you've triggered might be in preparation of the upcoming string type SplString.

In theory it behaves like a string, but since it is an object would pass the object type verification. Unfortunately it's not yet in PHP 5.3, might come in 5.4, so haven't tested this.

Solution 5

As of PHP 7.0 type declarations allow scalar types, so these types are now available: self, array, callable, bool, float, int, string. The first three were available in PHP 5, but the last four are new in PHP 7. If you use anything else (e.g. integer or boolean) that will be interpreted as a class name.

See the PHP manual for more information.

Share:
122,009

Related videos on Youtube

leepowers
Author by

leepowers

I work too much.

Updated on September 28, 2021

Comments

  • leepowers
    leepowers almost 3 years

    Here is my code:

    function phpwtf(string $s) {
        echo "$s\n";
    }
    phpwtf("Type hinting is da bomb");
    

    Which results in this error:

    Catchable fatal error: Argument 1 passed to phpwtf() must be an instance of string, string given

    It's more than a little Orwellian to see PHP recognize and reject the desired type in the same breath. There are five lights, damn it.

    What is the equivalent of type hinting for strings in PHP? Bonus consideration to the answer that explains exactly what is going on here.

    • Richard Knop
      Richard Knop over 13 years
      Well, that is because you are doing it wrong. Your code is not supposed to work, to begin with. Read up on type juggling in PHP docs. PHP is dynamic typed and weak typed. You can use (string) to cast an argument to string (only in function body though) but you can only hint objects and arrays like you do in your code snippet.
    • Pacerier
      Pacerier about 9 years
      @Gordon, I tested on 5.6. Still no luck.
    • Gordon
      Gordon about 9 years
      @Pacerier Please follow wiki.php.net/rfc for the latest developments.
    • Seldom 'Where's Monica' Needy
      Seldom 'Where's Monica' Needy over 8 years
      Apparently, scalar type-hinting (as OP intuitively expected to be a thing above) has finally been approved under an RFC for PHP *7* according to source. The approved RFC apparently also provides syntactic sugar for type-checking return-values as well as parameters (arguments). It's been a long time in the coming.
    • Axel
      Axel over 6 years
  • subosito
    subosito over 13 years
    You can add is_string() validation inside your function to prevent other value passed to the function.
  • Yanick Rochon
    Yanick Rochon over 13 years
    (string) $s may throw an error if $s is an object that cannot be cast into string (has no __toString() method implemented), so it's not as easy as that
  • subosito
    subosito over 13 years
    Yes Yanick you're right. But we can't forced all of input to be string right? that's why exception comes to play. We can combine sort of validations and catch exception for the rest ;)
  • Yanick Rochon
    Yanick Rochon over 13 years
    I'm just saying that casting some variable to string without checking first if the variable can be cast should be avoided, mainly because catching exceptions is costly and leads to bad design patterns / coding habbits.
  • Jimmy T.
    Jimmy T. almost 11 years
    I could still create a new string(array(1,2,3))
  • Pacerier
    Pacerier about 9 years
    @deceze, Is there a syntax for reverse type hinting? E.g. anything but arrays.
  • Gromski
    Gromski about 9 years
    @Pacerier No, there isn't.
  • Jose Nobile
    Jose Nobile over 8 years
    This answer is not valid for PHP 7
  • Ben Fransen
    Ben Fransen about 7 years
    Using $this when not in object context is indeed a cryptic message.