php - PDO 可以有带有类型化字符串参数的方法,但我不能在我自己的函数中执行此操作,这是怎么回事?

标签 php pdo type-hinting

如果我创建一个 PDO 实例,然后调用 PDO->Quote('test') ,它不会出现任何问题。

如果我查看 PDO Quote 方法的定义,它看起来像这样:

/**
 * Quotes a string for use in a query.
 * PDO::quote() places quotes around the input string (if required) and escapes special characters within the input string, using a quoting style appropriate to the underlying driver.
 *
 * @param string $string The string to be quoted.
 * @param int $parameter_type Provides a data type hint for drivers that have alternate quoting styles.
 *
 * return string
 */
function quote(string $string, int $parameter_type) {/* method implementation */}

请注意,参数实际上具有方法签名中定义的类型,string 和 int。

现在,如果我创建一个这样的函数:

function Test(string $test) {
    return $test;
}

并尝试这样调用它:

echo Test('test');

失败并出现以下错误:

( ! ) Catchable fatal error: Argument 1 passed to Test() must be an instance of string, string given, called in [path_removed]TestTypeHinting.php on line 36 and defined in [path_removed]TestTypeHinting.php on line 2

为什么PDO可以做到,而我却不行?

问候,

斯科特

最佳答案

像 string 和 int 这样的简单标量类型不能用作类型提示。我认为您在 pdo 上看到的字符串是文档中人类的类型提示。 http://php.net/manual/en/language.oop5.typehinting.php

世界已经改变

随着 PHP 7 的推出 scalar type hints现在是一件事。

关于php - PDO 可以有带有类型化字符串参数的方法,但我不能在我自己的函数中执行此操作,这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16643608/

相关文章:

python - 键入多种类型的提示值?

symfony - Hwi oauth bundle 和 Symfony 3.4 无法 Autowiring 服务 : How to use hwi/oauth-bundle in symfony 3. 4 + FOSUserBundle

javascript - 在 iframe 中嵌入谷歌地图时,如何删除附近的地点?

php - 复杂的多表mysql查询

php - 准备好的语句不返回任何行

PHP/MYSQL - 检索多个结果并创建数组

android - 插入脚本返回成功,但没有任何内容插入到数据库中

python - 键入具有特定列的提示 pandas 数据框

php - HighCharts - 使用 MySQL 和 PHP 制作饼图

php - behat undefined step 虽然它应该被定义