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

后端 未结 9 1244
情话喂你
情话喂你 2020-11-27 10:32

Here is my code:

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

Which results in this error:

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 11:04

    (originally posted by leepowers in his question)

    The error message is confusing for one big reason:

    Primitive type names are not reserved in PHP

    The following are all valid class declarations:

    class string { }
    class int { }
    class float { }
    class double { }
    

    My mistake was in thinking that the error message was referring solely to the string primitive type - the word 'instance' should have given me pause. An example to illustrate further:

    class string { }
    $n = 1234;
    $s1 = (string)$n;
    $s2 = new string();
    $a = array('no', 'yes');
    printf("\$s1 - primitive string? %s - string instance? %s\n",
            $a[is_string($s1)], $a[is_a($s1, 'string')]);
    printf("\$s2 - primitive string? %s - string instance? %s\n",
            $a[is_string($s2)], $a[is_a($s2, 'string')]);
    

    Output:

    $s1 - primitive string? yes - string instance? no

    $s2 - primitive string? no - string instance? yes

    In PHP it's possible for a string to be a string except when it's actually a string. As with any language that uses implicit type conversion, context is everything.

提交回复
热议问题