douxunchen3498 2014-11-21 08:42
浏览 28
已采纳

为什么通过函数包含的PHP会返回与主文件中的PHP不同的结果?

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?

  • 写回答

1条回答 默认 最新

  • doxn43207 2014-11-21 08:49
    关注

    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 :-)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!