Search code examples
phpwordpressfunctionfor-loopphp-include

Why would PHP included via a function return a different result from the PHP in the main file?


I'm trying to run a loop on WordPress that returns user information. When I have the PHP code to echo the results in the same file as the query, it works as expected. However, if I use include to access a transformation held elsewhere, it doesn't return any information, even if the code in the included file is identical. Why would this be?

My loop is below:

<?php

// The Query
$user_query = new WP_User_Query( array( 'include' => array( 1, 2, 3 ) ) );
// User Loop
if ( ! empty( $user_query->results ) ) {
    foreach ( $user_query->results as $user ) {
?>

<?php transform('user_directory'); echo $user->display_name; ?>

<?php
    }
} else {
    echo 'No users found.';
}
?>

Transform is a simple function that includes another page by name:

function transform($transformation) {
    include 'transformations/'.$transformation.'.php';
}

In this case, the echo command works, whereas the included file (via Transform) doesn't. The included file is definitely being found and is rendering other html and PHP code perfectly, it just doesn't seem able to find anything under $user.

The code held in the included PHP file is:

<?php echo $user->display_name; //Won't return this text
echo "It returns this text fine"; ?>

Am I not able to access an array created on one page with included code from another?


Solution

  • The problem is, you are including it from a function. A function, in PHP, does have it's own scope. The included file will inherit the, empty, scope of the function. You could pass the $user to the function:

    function transform($transformation, $user) {
        include 'transformations/'.$transformation.'.php';
    }
    
    ...
    
    <?php transform('user_directory', $user); echo $user->display_name; ?>
    

    This will set the $user variable, and make it accessible by the included file.

    Hope this helps :-)