怎么PDO可以有类型字符串参数的方法,但我不能在我自己的函数中这样做?

怎么PDO可以有类型字符串参数的方法,但我不能在我自己的函数中这样做?

问题描述:

If I create an instance of PDO and then call PDO->Quote('test') it works no problems.

If I look at the defination of the PDO Quote method it looks like this:

/**
 * 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 */}

Note the parameters actully have types defined in the method signature, string and int.

Now if I create a function like this:

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

And attempt to call it like this:

echo Test('test');

It fails with the following error:

( ! ) 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

How come PDO can do it, but I can't?

Regards,

Scott

如果我创建一个PDO实例,然后调用PDO-> Quote('test')它没有问题 。 p>

如果我看一下PDO Quote方法的定义,它看起来像这样: p>

  / ** 
 *引用a 在查询中使用的字符串。
 * PDO :: quote()在输入字符串周围放置引号(如果需要),并使用适合底层驱动程序的引用样式转义输入字符串中的特殊字符。
 * 
  * @param string $ string要引用的字符串。
 * @param int $ parameter_type为具有备用引用样式的驱动程序提供数据类型提示。
 * 
 * return string 
 * / 
function quote(string  $ string,int $ parameter_type){/ *方法实现* /} 
  code>  pre> 
 
 

请注意,参数actully具有在方法签名,字符串和int中定义的类型。 p>

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

  function Test(string $ test){
 return $ test; 
  } 
  code>  pre> 
 
 

并尝试这样调用它: p>

  echo Test('test'); 
   code>  pre> 
 
 

失败并出现以下错误: p>

 (!)可捕获的致命错误:参数1传递给Test() 必须是字符串的实例,给定字符串,在第36行的[path_removed] TestTypeHinting.php中调用,并在第2行的[path_removed] TestTypeHinting.php中定义
  code>  pre> 
 
 

为什么PDO可以做到,但我不能呢? p>

问候, p>

Scott p> div>

It's documentation and the real code. Read about type hinting.

Type hints can not be used with scalar types such as int or string

But there is some moving to implement scalar type hinting.

You can add phpdoc for documentation your function.

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

Also read about How to read a function definition

Simple scalar types like string and int cannot be used as a type hint. I think the string you saw on pdo was type hinting for humans in the documentation. http://php.net/manual/en/language.oop5.typehinting.php

The world has changed

With the introduction of PHP 7 scalar type hints are now a thing.