require/include into variable

前端 未结 9 1599
萌比男神i
萌比男神i 2020-11-27 17:46

I want to require/include a file and retrieve its contents into a variable.

test.php



        
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 18:13

    In PHP/7 you can use a self-invoking anonymous function to accomplish simple encapsulation and prevent global scope from polluting with random global variables:

    return (function () {
        // Local variables (not exported)
        $current_time = time();
        $reference_time = '01-01-1970 00:00';
    
        return "seconds passed since $reference_time GMT is $current_time";
    })();
    

    An alternative syntax for PHP/5.3+ would be:

    return call_user_func(function(){
        // Local variables (not exported)
        $current_time = time();
        $reference_time = '01-01-1970 00:00';
    
        return "seconds passed since $reference_time GMT is $current_time";
    });
    

    You can then choose the variable name as usual:

    $banner = require 'test.php';
    

提交回复
热议问题