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?
Type hinting is a concept that provides hints to function for the expected data type of arguments. For example, If we want to add an integer while writing the add function, we had mentioned the data type (integer in this case) of the parameter.
In simple word, type hinting means providing hints to function to only accept the given data type. In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type. In PHP, we can use type hinting for Object, Array and callable data type.
The PHP Type Hinting works for only some type of data. For functions arg/argument, the user will specify some user-defined class instance and it will be hinted by the class name. It works after the PHP 5 version. It works by specifying the data type for variables, functions, etc.
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With