5

While working on the following code I noticed that declare(strict_types=1) has no effect on the arguments of a callback function through array_walk()

<?php
declare(strict_types=1);

function myCallBack(int $value, $key) {

    echo $value;
}

function myFunc(int $value, $key) {
    echo $value;
}

$myArr = array("eggs" => 4, "Butter" => 4, "meat" => 4.5);

echo 'myCallBack..';
array_walk($myArr, 'myCallBack'); // Output: 444 

echo ' <br />myFunc..';
myFunc(4.2, 'eggs'); // Output:Fatal error: Uncaught TypeError: Argument 1 passed to myFunc() must be of the type integer

?>

I'm expecting php to throw an exception instead of 444 because [meat] value in $myArr is not integer!

apparently php ignores the fact that [meat] in $myArr is float for some reason! instead of throwing an exception just like what happened with myFunc().

Is this a normal php behavior or am I missing something?.

Nik
  • 2,885
  • 2
  • 25
  • 25
Rain
  • 3,416
  • 3
  • 24
  • 40
  • 2
    After asking in the PHP room, NikiC replied: _strict types is determined by calling scope. Internal code is always weak. Callbacks called from internal code will always use weak types. It's a common issue_ See the logs here: https://chat.stackoverflow.com/transcript/message/40320863#40320863 – icecub Dec 05 '17 at 18:19
  • 1
    [Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.](https://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict) – PeeHaa Dec 05 '17 at 18:51
  • 1
    `myCallBack` is not called in your code. You only passed the name (as string) in some other function (`array_walk`). That (internal) function eventually executes your callback. – PeeHaa Dec 05 '17 at 19:14
  • @PeeHaa Ok, then why when i use call_user_func() instead of array_walk() php actually throws an exception ? aren't they both (internal) functions? – Rain Dec 05 '17 at 20:00
  • 2
    @FatalError The call_user_func case is a bug. call_user_func is converted into a direct function call, if possible. It should be always-weak, but isn't because of this optimization. – NikiC Dec 05 '17 at 23:47

0 Answers0