unexpected T_FUNCTION with php 5.2.17 but fine on

2019-02-24 18:05发布

问题:

I"m getting an unexpected T_FUNCTION php error after uploading my Wordpress files to a server running php version 5.2.17.

The theme works fine on localhost (with MAMP) and there are also no errors on my own server which runs php version 5.3.10.

What can be wrong or what can be done to solve this error?

This is the line that causes the error:

add_action('init', function() use($name, $args) {   

And the entire functions.php file looks like this:

<?php 

/* Add Post Type */
function add_post_type($name, $args = array() ) {   
    if ( !isset($name) ) return;

    $name = strtolower(str_replace(' ', '_', $name));

    add_action('init', function() use($name, $args) {   
        $args = array_merge(
            array(
                'label' => 'Members ' . ucwords($name) . '',
                'labels' => array('add_new_item' => "Add New $name"),
                'singular_name' => $name,
                'public' => true,
                'supports' => array('title', 'editor', 'comments'),
            ),
            $args
        );

        register_post_type( $name, $args);
    });
}


add_post_type('Netherlands', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));


add_post_type('Belgium', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

    add_post_type('Germany', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

    add_post_type('France', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

    add_post_type('United-Kingdom', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

    add_post_type('Ireland', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

    add_post_type('Spain', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

    add_post_type('Portugal', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

    add_post_type('Italy', array(
    'supports' => array('title', 'editor', 'thumbnail', 'comments')
));

I'm really new to php and only use it for Wordpress theming. Any help is really appreciated.

回答1:

You cannot have anonymous functions in PHP less than 5.3

Rework your code so that it does not involve anonymous functions and it should work on your older server.



回答2:

add_action()'s second parameter is of type callback.

Pre 5.3, this is usually a string representing a function:

add_action('init', 'myFunction');

function myFunction() { echo 'init'; }

There are alternatives such as create_function and other syntaxes to use when dealing with objects.

5.3 onward, anonymous functions are allowed:

add_action('init', function() { echo 'init'; });


回答3:

anonymous functions available from PHP 5.3.0



标签: php wordpress