Michael
Michael

Reputation: 4876

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?

Upvotes: 8

Views: 3392

Answers (3)

Joako-stackoverflow
Joako-stackoverflow

Reputation: 516

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

Upvotes: 4

Ynhockey
Ynhockey

Reputation: 3932

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.

Upvotes: 2

Eric Lavoie
Eric Lavoie

Reputation: 5431

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 :

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

Upvotes: 3

Related Questions