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

0 votes

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

Apr 20 in PHP by kartik
• 11,290 points
47 views

1 answer to this question.

+1 vote

Hello,

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;
    }
    ...
}
answered Apr 20 by I Navin
• 220 points

Related Questions In PHP

0 votes
1 answer

How to validate E-mail and URL of Php form?

hey, The code below shows a simple way ...READ MORE

answered Feb 13 in PHP by manish
81 views
0 votes
1 answer

How to merge two arrays while keeping keys instead of reindexing in php?

Hello, Considering that you have $replaced = array('1' => ...READ MORE

answered Apr 1 in PHP by Niroj
• 22,790 points
38 views
0 votes
0 answers
0 votes
1 answer

How to pass an array within a query string?

Hello, Submitting multi-value form fields, i.e. submitting arrays ...READ MORE

answered Apr 7 in PHP by Niroj
• 22,790 points
68 views
0 votes
1 answer

How to put an 'if clause' in an SQL string?

Hello @kartik, For your specific query, you can ...READ MORE

answered 1 day ago in PHP by Niroj
• 22,790 points
12 views
0 votes
1 answer

How to make anchor tag with routing using Laravel?

Hey @kartik, First you have to go to ...READ MORE

answered Mar 18 in Laravel by Niroj
• 22,790 points
434 views
0 votes
1 answer

What is redirection in Laravel?

Named route is used to give specific ...READ MORE

answered Mar 18 in Laravel by Niroj
• 22,790 points
62 views
0 votes
1 answer

How to install Laravel via composer?

Hello, This is simple you just need to ...READ MORE

answered Mar 23 in Laravel by Niroj
• 22,790 points
64 views
0 votes
1 answer

What are named routes in Laravel and How can specify route names for controller actions?

Hey @kartik, Named routing is another amazing feature of ...READ MORE

answered Mar 23 in Laravel by Niroj
• 22,790 points
151 views
0 votes
1 answer

How to set up file permissions for Laravel?

Hello @kartik, The permissions for the storage and vendor folders should stay ...READ MORE

answered Apr 20 in PHP by I Navin
• 220 points
34 views