简体   繁体   中英

PHP type hinting error?

I just got this Fatal Error

Catchable fatal error: Argument 1 passed to File::__construct() must be an instance of integer, integer given, called in /home/radu/php_projects/audio_player/index.php on line 9 and defined in /home/radu/php_projects/audio_player/php/File.php on line 7

So, there is the class

class File{        
        public $id;
        public $name;
        public $file_paths;
        public function __construct(integer $id=null, string $name=null, array $file_paths=null)
        {
            foreach(func_get_args() as $name => $val)
            {
                $this->$name = $val;
            }
        }
    }

And here is the code that triggers the error

$file = new File(1, "sound", array());

Am I missing something or there is something bad with this PHP type hinting?

As far as I know, you can't use the integer type hint in PHP. However, someone in PHP.net had this helpful comment:

http://www.php.net/manual/en/language.oop5.typehinting.php#83442

It's apparently a workaround that will work for you if you really need this functionality.

You can't force a parameter to be an integer.

Look here language.oop5.typehinting :

PHP 5 introduces type hinting. Functions are now able to force parameters to be objects [...], interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4).

[...]

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

And here language.types.intro , PHP scalar types are :

\n- boolean \n- integer \n- float (floating-point number, aka double) \n- string \n

Since this could be misleading and since this answer is still quite high in search engines.

PHP 7 did introduce type hinting for scalar types

There is no scalar type hinting in PHP 5, so the integer type hint is considered to be a class type hint.

More reference http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM