简体   繁体   中英

Function name conflict when including a PHP file in a WordPress Theme

I am a PHP novice, so bear with me if any of my terminology is incorrect.

I have a small PHP file ( page_class.php ) that defines some functions and I include this file in the header.php of my theme:

<?php include("page_class.php"); ?>

And these are the contents of page_class.php :

<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

function get_subdomain() {
    $page_url = curPageURL();
    $parts = split('\.', $_SERVER["SERVER_NAME"]);
    return $parts[0];
}

function get_body_class() {
    $subdomain = get_subdomain();
    if ($subdomain == "keyes") {
        $path_parts = split('/', $_SERVER["REQUEST_URI"]);
        $clazz = $path_parts[1];
    }
    else {
        $clazz = $subdomain;
    }
    if ($clazz == "greasemonkey" || $clazz == "wordpress") {
        $clazz = "work";
    }
    if ($clazz == "") {
        $clazz = "home";
    }
    return $clazz;
}
?>

I call get_body_class in header.php :

<body class="<?php echo get_body_class(); ?>">

This setup worked in WordPress MU 2.7.1. I recently upgraded to 2.8.6 and it broke. When I visited any page on the blog the screen was blank.

After some investigation I figured out that by changing the function names (I prefixed them with jk_ ) it worked again.

I guessed this was a naming conflict, but couldn't find any. I wonder do any PHP or WordPress devs have any idea why this happens.

get_body_class() seems in fact to be there since 2.8 . You're not the only one who had the problem: See here .

By the way, while it is the right thing to have error reporting turned off on a production server, you may want to turn it up some if you get errors like that.

error_reporting(E_ALL ^ E_NOTICE);

I've just downloaded the sources of wordpress 2.9 (not exactly the same version as yours, I admit, but it's the last one, and the easiest to get from wordpress.org), and it seems there is already an existing get_body_class function :

$ grep -rn 'get_body_class' *
wp-includes/post-template.php:354:      echo 'class="' . join( ' ', get_body_class( $class ) ) . '"';
wp-includes/post-template.php:365:function get_body_class( $class = '' ) {

It seems that function is defined in post-template.php (line 365 in wordpress 2.9) ; which explains the conflict, as it's not possible to have two functions with the same name, in PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM