doumiebiao6827 2013-07-24 17:57
浏览 21
已采纳

具有已知参数的数组

I've not that new to php but am trying to figure out how exactly this piece of code reads.

$actions = array();  

function add_action( $hook, $function )  
{  
    global $actions;  

    // create an array of function handlers if it doesn't already exist  
    if( !isset( $actions[ $hook ] ) )  
        $actions[ $hook ] = array();  

    // append the current function to the list of function handlers  
    $actions[ $hook ][] = $function;  
}  

here is my understanding but I believe I'm completely wrong - variable actions is given an array with no params, then a function is created and actions is made into a global giving it global scope. Then there a condition the bit I don't understand that somehow checks for a parem. $actions[ $hook ] its what this bit means that confuses me. is it calling into the array? and why are blank arrays set to variables?

Thanks for clearing this up for me

  • 写回答

3条回答 默认 最新

  • dtczp02204 2013-07-24 18:13
    关注

    First we are declaring a php variable $actions within the global scope:

    $actions = array();
    

    Then in the function, you use the global keyword to declare that you are using an already defined global value instead of creating a new value within the scope of the function:

    global $actions;
    

    Next, it is using the isset() function to check if the value $hook exists as an index of our global $actions. If the index does not exist, it creates that index and assigns it an empty array as the value.

    // create an array of function handlers if it doesn't already exist  
    if( !isset( $actions[ $hook ] ) )  
        $actions[ $hook ] = array();
    

    Last, it is using the bracket operator on the array it was just given to append a new value to it, in this case it is giving it the value of $function.

    // append the current function to the list of function handlers  
    $actions[ $hook ][] = $function;  
    

    So in the end, you have the global $actions variable with an index of $hook which has an array value, and that array value has an index added to it with the value of $function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大