传递给myFunction()的参数1必须是string, string given, called in的实例



我有这个功能:

function myFunction(string $name) {
    $db = mysql_connect("localhost", "root", "");
    mysql_select_db(...); 
    $insertplayer="INSERT INTO `...`(....)
    VALUES (......')";
    if (!mysql_query($insertplayer,$db))
      {
      die('Error: ' . mysql_error());
      }
    $id = mysql_insert_id();
    echo 'done for player N°'.$id;
    mysql_close($db);
}

和我使用的形式:

<form action="insertplayer.php" method="post">
    <input type="text" name="nameplayer" />
    <input type="submit" value="ok" />
</form>

但是当我这样做的时候,我有这个错误:

Catchable fatal error: Argument 1 passed to myFunction() must be an instance of string, string given, called in C:.... on line 23 and defined in C:...

我在整型问题上有这个错误。

尝试从函数声明中删除原始数据类型。对于基本数据类型,PHP不需要类型提示。

function myFunction($name) {
    $db = mysql_connect("localhost", "root", "");
    mysql_select_db(...); 
    $insertplayer="INSERT INTO `...`(....)
    VALUES (......')";
    if (!mysql_query($insertplayer,$db))
      {
      die('Error: ' . mysql_error());
      }
    $id = mysql_insert_id();
    echo 'done for player N°'.$id;
    mysql_close($db);
}

如果你不想在每个函数的开头写一段代码来检查类型,你可以这样写:

function myFunction($myScalar) {
    if (!is_string($myScalar)) {
        throw new Exception(...);
    }
    ...
}

你可以注册一个错误处理程序,比较给定的类型和你的提示,如果例如string==string,你可以忽略错误。

请参阅手册页的用户注意以获得一些示例

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

相关内容

最新更新