John Davidson

Can a PHP function expect a type?

0 comments
Message:


I'm trying to do something like this:


function get_value($value)
{
if (is_null($value)) {
if ($value expects array) {
return ['hello', 'world'];
}
else {
return 'hello world';
}
}

return $value;
}

So that I can call it in an echo or a foreach like this:


$value = null;

foreach(get_value($value) as $value) {
echo $value;
}

echo get_value($value);

So the foreach would expect an array, but the echo would expect a string.


Is this possible?



My Answer:
No, PHP does not have the ability to specify the type of a parameter in a function declaration. PHP is a dynamically typed language, which means that the type of a variable is determined at runtime based on the value assigned to it.

In your example, you can achieve the desired behavior by checking the type of the value inside the function using functions like `is_array()` or `is_string()` and returning the appropriate value. However, you cannot enforce the type of the parameter in the function declaration itself.

Rate this post

3 of 5 based on 3304 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us