I have defined a function like this:
private function mediaExist(string $entry) { ...
and I'm getting this type of error:
... must be an instance of string, string given, called in ...
Any help ?
PHP type-hints only work for classes or arrays:
function foo(array $bar, stdClass $object)
{//fine
}
But you can't type-hint primitives/scalar or resource types:
function bar(int $num, string $str)
{}
This would invoke the autoloader, which in term will attempt to find class definitions for the int
and string
classes, which obviously don't exist.
The rationale behind this is quite simple. PHP is a loosely typed language, and a numeric string can be turned into an int, or float, through type-juggling:
$foo = '123';
$bar = $foo*2;//foo's value is used as an int -> 123*2
type-hints were introduced to improve the OO capabilities of the language: a class/interface should be able to enforce a contract, through use of (among other things) type hinting.
If you want to ensure a given value is a string, you can use casts, or type-checking functions:
function foo($string)
{
$sureString = (string) $string;//cast to string
if ($sureString != $string)
{//loose comparison, if they are not equal, the argument could not be converted to a string reliable
throw new InvalidArgumentException(__FUNCTION__.' expects a string argument, '.get_type($string).' given');
}
}
As far as resources are concerned (things like a file handler), it's just as easy to fix:
function foobar(/* resource hint is not allowed */ $resource)
{
if (!is_resource($resource))
{
throw new InvalidArgumentException(
sprintf(
'%s expects a resource, %s given',
__FUNCTION__,
get_type($resource)
);
);
}
}
In the end, the best thing to do when developing a sizable PHP project is to use doc-blocks, and a decent IDE. When you call a function/method, the IDE will use the doc-blocks to tell you what types are expected. It's the programmers job to ensure those criteria are met:
/**
* Some documentation: what this function does, and how the arguments
* are being used
* @param array $data
* @param string $key
* @param string $errorMsg = ''
* @return mixed
* @throws InvalidArgumentException
**/
function doStuff(array $data, $key, $errorMsg = '')
{
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加