如果我创建一个 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/