This might sound like a silly question to many of you, but it keeps me wondering why PHP does not allow typecasting in its function parameters. Many people use this method to cast into their parameters:
private function dummy($id,$string){
echo (int)$id." ".(string)$string
}
Or
private function dummy($id,$string){
$number=(int)$id;
$name=(string)$string;
echo $number." ".$name;
}
But looking at many other programming languages, they accept typecasting into their function parameters. But doing this in PHP may lead to errors.
private function dummy((int)$id,(string)$string){
echo $id." ".$string;
}
Parse error: syntax error, unexpected T_INT_CAST, expecting '&' or T_VARIABLE
Or
private function dummy(intval($id),strval($string)){
echo $id." ".$string;
}
Parse error: syntax error, unexpected '(', expecting '&' or T_VARIABLE
Just want to know why this does not work and if there is a way. If there is no way, then going to the regular way is alright for me:
private function dummy($id,$string){
echo (int)$id." ".(string)$string;
}
PHP does have a rudimentary type-hinting ability for arrays and objects, but it doesn't work on scalar types.
PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function prototype), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.
If class or interface is specified as type hint then all its children or implementations are allow>ed too.
Type hints can not be used with scalar types such as int or string. Traits are not allowed either.
public function needs_array(array $arr) {
var_dump($arr);
}
public function needs_myClass(myClass $obj) {
var_dump($obj);
}
If you need to enforce a scalar type, you will need to do it by typecasting or checking the type in the function and bailing out or acting accordingly if it receives the wrong type.
public function needs_int_and_string($int, $str) {
if (!ctype_digit(strval($int)) {
throw new Exception('$int must be an int');
}
if (strval($str) !== $str) {
throw new Exception('$str must be a string');
}
}
public function needs_int_and_string($int, $str) {
$int = intval($int);
$str = strval($str);
}
PHP 7 has introduced Scalar type declarations with strict and non-strict modes. It is now possible to throw a TypeError
in strict mode if a function argument variable does not exactly match the declared type, or to coerce the type in non-strict mode.
declare(strict_types=1);
function int_only(int $i) {
// echo $i;
}
$input_string = "123"; // string
int_only($input);
// TypeError: Argument 1 passed to int_only() must be of the type integer, string given
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