how is it that PDO can have methods with typed string parameters, but I can't do this in my own functions?

StackOverflow https://stackoverflow.com/questions/16643608

  •  30-05-2022
  •  | 
  •  

Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top