0

Why does it only first example not work? What does it happen with the function_exists if it under array_walk? Is it working compiler so, php stack, scope?

I didn't found any explain about it. Or may be I found but didn't understand.

  1. It doesn't work and throw exception: Warning: array_walk() expects parameter 2 to be a valid callback, function 'test_print' not found or invalid function name in /var/www/sandbox.php on line 4
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

array_walk($fruits, 'test_print');
if(!function_exists('test_print')) {
    function test_print($item2, $key)
    {
        echo "$key. $item2<br />\n";
    }
}
  1. It works
<?php 
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

if(!function_exists('test_print')) {
    function test_print($item2, $key)
    {
        echo "$key. $item2<br />\n";
    }
}
array_walk($fruits, 'test_print');
  1. It works
<?php 
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

   function test_print($item2, $key)
   {
       echo "$key. $item2<br />\n";
   }

array_walk($fruits, 'test_print');
  1. It works
<?php 
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

array_walk($fruits, 'test_print');

function test_print($item2, $key)
{
     echo "$key. $item2<br />\n";
}

php sandbox if you need

Shturmavik
  • 304
  • 2
  • 6
  • 1
    It's because you're trying to use it before it's defined. – El_Vanja Nov 30 '20 at 20:55
  • Why do you expect the function to work if it doesn't exist yet? Though, the last example is curious – GrumpyCrouton Nov 30 '20 at 20:55
  • 4
    From [the documentation](https://www.php.net/manual/en/functions.user-defined.php): *Functions need not be defined before they are referenced, **except when a function is conditionally defined** as shown in the two examples below.* – iainn Nov 30 '20 at 20:58
  • @iainn thank you much. I understood at last. – Shturmavik Nov 30 '20 at 21:05
  • 3
    @GrumpyCrouton Last example works due to hoisting. Non-conditional function definitions are moved to the top of their scope before execution. – El_Vanja Nov 30 '20 at 21:13

0 Answers0