Return from include file

前端 未结 5 1041
醉酒成梦
醉酒成梦 2020-11-27 17:41

in PHP, how would one return from an included script back to the script where it had been included from?

IE:

1 - main script 2 - application 3 - included

相关标签:
5条回答
  • 2020-11-27 17:44

    I know that this has already been answered, but I think I have a nice solution...

    main.php

    function test()
    {
        $data = 'test';
        ob_start();
            include( dirname ( __FILE__ ) . '/included.php' );
        return ob_get_clean();
    }
    

    included.php

    <h1>Test Content</h1>
    <p>This is the data: <?php echo $data; ?></p>
    

    I just included $data to show that you can still pass data to the included file, as well as return the included file.

    0 讨论(0)
  • 2020-11-27 17:50

    return should work, as stated in the documentation.

    If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call.

    0 讨论(0)
  • 2020-11-27 17:51

    Hm, the PHP manual disagrees with you. return should bail you out of an included file. It won't work from within a function, of course.

    0 讨论(0)
  • 2020-11-27 17:52

    See Example #5 in the documentation for include.

    You can get the return value of the script when including it, like:

    $foo = include 'script.php';
    
    0 讨论(0)
  • 2020-11-27 17:54

    includeme.php:

    $x = 5;
    return $x;
    

    main.php:

    $myX = require 'includeme.php'; 
    

    also gives the same result

    This is one of those little-known features of PHP, but it can be kind of nice for setting up really simple config files.

    0 讨论(0)
提交回复
热议问题