Make WordPress Core

Opened 4 years ago

Last modified 3 years ago

#40284 new defect (bug)

Something weird on do_action function in passing an array

Reported by: wolfkang Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 4.7.3
Component: Plugins Keywords:
Focuses: Cc:



I found something weird on do_action function.

In do_action function, the first argument is replaced with its first element if it is an array and it has only one object element.

For example,

add_action('my_action', 'my_action', 10, 1);
function my_action($posts = array()) {
    echo gettype($posts);
$posts = array();
$posts[] = get_post(1);
do_action('my_action', $posts);  // prints "object" in my_action
$posts[] = get_post(3);
do_action('my_action', $posts);  // prints "array" in my_action

The do_action codes are here.

$args = array();
if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
        $args[] =& $arg[0];
        $args[] = $arg;
for ( $a = 2, $num = func_num_args(); $a < $num; $a++ )
        $args[] = func_get_arg($a);

I don't understand how come it's necessary that do_action replaces an array argument with its element.
I think do_action should be modified like this.

$args = array();
for ( $a = 1, $num = func_num_args(); $a < $num; $a++ )
        $args[] = func_get_arg($a);

Otherwise, I must check if the argument is an array or not in the my_action function.

Please check this out.


Change History (1)

#1 @swissspidy
3 years ago

#44638 was marked as a duplicate.

Note: See TracTickets for help on using tickets.