In php, can I access the elements of the current array by index?

In php, can I access the elements of the current array by index? Example:

$arr = array( 'index1' => function() { echo 'foo'; //foo }, 'index2' => function() { $arr['index1']() // foo ?????????? echo 'bar'; //bar } ); 

How to call $arr['index1']() in $arr ?

+4
source share
1 answer

The problem is that $arr is a variable defined outside the function, so it is impossible to access from it.

Try just importing the $arr variable into the closure with use ($arr) , but that will not work, because $arr is not really defined at the time you define your function.

While $arr truly a global variable, you can update such a function to make it work:

 'index2' => function() { global $arr; $arr['index1'](); // foo echo 'bar'; //bar } 

A better idea is to pass an array as a parameter to a function, for example:

 'index2' => function($a) { $a['index1'](); // foo echo 'bar'; //bar } 

... and name it as follows:

 $arr['index2']($arr); 
+4
source

Source: https://habr.com/ru/post/1489831/


All Articles