WordPress.org

Make WordPress Core

Opened 15 months 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:

Description

Hi,

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. https://core.trac.wordpress.org/browser/tags/4.7/src/wp-includes/plugin.php#L421

$args = array();
if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this)
        $args[] =& $arg[0];
else
        $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.

Regards

Change History (0)

Note: See TracTickets for help on using tickets.