Php 为什么PDO可以有带类型化字符串参数的方法,而我可以';我不能在我自己的功能中这样做吗?

Php 为什么PDO可以有带类型化字符串参数的方法,而我可以';我不能在我自己的功能中这样做吗?,php,pdo,type-hinting,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

如果我创建一个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 */}
function Test(string $test) {
    return $test;
}
注意,参数实际上具有在方法签名、字符串和int中定义的类型

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

/**
 * 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 */}
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能做到,但我不能

问候,


Scott

这是文档和真正的代码。了解

类型提示不能与int或string等标量类型一起使用

但仍有一些措施需要实施

您可以为函数添加phpdoc文档

/**
 * Test function
 * @param string $test
 * @return string
 */
function Test($test) {
    return $test;
}

另外,请阅读

字符串和int等简单标量类型不能用作类型提示。我认为您在pdo上看到的字符串是文档中对人类的类型暗示

世界变了


随着PHP7的引入,现在已经成为了一件事

谢谢你的回复。是的,我看过doco,基于这一点,我理解为什么我不能这么做,但是为什么PDO可以公开一个带有类型化字符串参数的PHP API呢?@user2109254,看看添加的linksectus,再次感谢mate。所以我在上面看到的只是描述应该传入的内容的文档,而不是底层方法签名的准确表示,因为在PHP中,可以对标量类型使用类型提示?如果是这种情况,他们应该坚持使用标准的方法文档格式:@param string$string要引用的字符串。您在哪里看到了PDO代码?我正在使用Visual Studio 2012和用于Visual Studio扩展的PHP工具。它有intellisence for PHP,您也可以右键单击一个方法,然后从上下文菜单中选择Go To Definition,它将跳转到承载该方法的文件。我这样做时打开的文件是:C:\Users[accountNameRemoved]\AppData\Local\Temp\137E147D$allphpnet.xml\global$class$PDO.php,文件选项卡显示:global$class$PDO.php[来自元数据]。。。。就像它显示了一个DLL API…那么这只是VS提供的一个类型提示,所以它可以输入提示。它不是实际的PHP代码。hmmm。。。。我想知道VS是如何知道param应该是一个字符串的,仅仅是从PHPDoc,也许他们会推断出来?我可能会问那些制作PHP工具的人,看看他们怎么想;-)是的,它可能是从文档或源代码自动生成的。谢谢您的回复。我想我现在明白了。然而,我认为这是一种误导,如果只是doco,那么他们应该使用标准的PHPDoc格式,并保留方法签名以遵守PHP语言规则。它可能来自PHPDoc之类的工具。