setting scope of array_map php

大城市里の小女人 提交于 2019-12-19 09:39:26

问题


hey all, i use array_map from time to time to write recursive methods. for example

function stripSlashesRecursive( $value ){

    $value = is_array($value) ?
        array_map( 'stripSlashesRecursive', $value) :
    stripslashes( $value );
    return $value;
}

Question:

say i wanna put this function in a static class, how would i use array_map back to the scope of the static method in the class like Sanitize::stripSlashesRecursive(); Im sure this is simple but i just cant figgure it out, looked at php.net as well.


回答1:


When using a class method as a callback for functions like array_map() and usort(), you have to send the callback as two-value array. The 2nd value is always the name of the method as a string. The 1st value is the context (class name or object)

// Static outside of class context
array_map( array( 'ClassName', 'methodName' ), $array );

// Static inside class context
array_map( array( __CLASS__, 'methodName' ), $array );

// Non-static outside of object context
array_map( array( $object, 'methodName' ), $array );

// Non-static inside of object context
array_map( array( $this, 'methodName' ), $array );



回答2:


array_map takes a callback as its first parameter.

And a callback to a static method is written like this :

array('classname', 'methodname')


Which means that, in your specific case, you'd use :

array_map(array('stripSlashesRecursive', ''), $value);


For more informations about callbacks, see this section of the PHP manual : Pseudo-types and variables used in this documentation - callback.




回答3:


array_map( array('Sanitize', 'stripSlashesRecursive'), $value) ...


来源:https://stackoverflow.com/questions/2329483/setting-scope-of-array-map-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!