Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/236.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 传递给的参数1必须是int的实例,给定整数_Php_Mysql - Fatal编程技术网

Php 传递给的参数1必须是int的实例,给定整数

Php 传递给的参数1必须是int的实例,给定整数,php,mysql,Php,Mysql,我刚刚开始学习php,下面是一个例子 但在我尝试运行时出现错误“传递给的参数1必须是int的实例,给定的整数…”: <?php require_once 'dbconfig.php'; /** * Get customer level * @param int $customerNumber * @return string */ function getCustomerLevel(int $customerNumb

我刚刚开始学习php,下面是一个例子

但在我尝试运行时出现错误“传递给的参数1必须是int的实例,给定的整数…”:

   <?php

    require_once 'dbconfig.php';

    /**
     * Get customer level
     * @param int $customerNumber
     * @return string
     */
    function getCustomerLevel(int $customerNumber) {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

            // calling stored procedure command
            $sql = 'CALL GetCustomerLevel(:id,@level)';

            // prepare for execution of the stored procedure
            $stmt = $pdo->prepare($sql);

            // pass value to the command
            $stmt->bindParam(':id', $customerNumber, PDO::PARAM_INT);

            // execute the stored procedure
            $stmt->execute();

            $stmt->closeCursor();

            // execute the second query to get customer's level
            $row = $pdo->query("SELECT @level AS level")->fetch(PDO::FETCH_ASSOC);
            if ($row) {
                return $row !== false ? $row['level'] : null;
            }
        } catch (PDOException $e) {
            die("Error occurred:" . $e->getMessage());
        }
        return null;
    }

    $customerNo = 103;
    echo sprintf('Customer #%d is %s', $customerNo, getCustomerLevel($customerNo));

无需在PHP中键入提示参数。但是,在某些情况下可以使用类型提示(它对类非常有用)。

在您的例子中,PHP需要一个未定义的int类实例。您可以使用is_int函数检查传递的参数是否为整数

您可以使用以下内容替换参数绑定:

  $stmt->bindParam(':id', $customerNumber);

在这种情况下不需要第三个参数。

标量类型(bool、int、float、string)的类型暗示/声明仅在PHP 7.0.0中受支持


请参见

听起来您运行的是PHP版本<7,其中标量类型声明还不可能。因此,只要删除此处的
int
表单:
getCustomerLevel(int$customerNumber)
升级到PHP7,如果可以的话。如果您只是在学习,不妨学习最新版本。我认为,除非您在代码中像示例那样定义它(不太可能)或键入cast-it,否则无论如何传递时它都将是一个字符串(来自
$\u POST
,DB等。那么为什么在这里强制
int
?这可能是真的,但问题与此无关。只需从函数调用中删除int,并在函数开始时使用if语句确定传递的参数是否为整数。如果不是,则可能返回错误(或null,因为这是您在函数中进一步返回的内容)我想你可能是这个意思,所以我这么做了,但现在看起来所有带有连接字符串的变量都不可识别:主机、数据库名、用户名和密码。连接没有问题。在代码段中,如果没有定义这些变量,则会出现此错误。起初,您没有收到此错误,因为函数无法初始化e到参数错误,意味着函数中的代码没有运行。现在参数错误消失了,函数中的错误确实出现了。我不认为是这种情况,在同一网页中有另一个调用存储过程示例(尽管没有输入我们的输出参数),并且连接的变量设置完全相同,我运行了.php,没有任何问题。好的,明白了。dbconfig.php不知何故不适用于此脚本。因此,我尝试设置$dsn、$username和$password,并再次定义$pdo,现在它工作正常。但是,是的,我删除了typehint。非常感谢您的帮助