Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

(I'm starting this question over from scratch. If you want to know what the original question was that MrMook attempted to answer, or the revised question that Progman commented on, see the edit history. I have now boiled down the behavior to the barest elements and ask the question anew based on that.)

I have created five files and their entire contents are as follows:

test-forward.php
    <?php
    require_once('script1.php');
    require_once('script2.php');
    ?>
test-backward.php
    <?php
    require_once('script2.php');
    require_once('script1.php');
    ?>
script1.php
    <?php
    SayHello()
    ?>
script2.php
    <?php
    function SayHello() {echo 'Hello';}
    ?>
test-together.php
    <?php
    SayHello();
    function SayHello() {echo 'Hello';}
    ?>

When I run either test-backward.php or test-together.php, the browser says Hello, and there is nothing added to PHP log file.

When I run test-forward.php, the browser is blank, and the PHP log file reports:

PHP Fatal error:  Uncaught Error: Call to undefined function SayHello() in ...script1.php:2

The script test-together.php shows that a function can be called before it is defined. My understanding is (as MrMook said) that included (or required) scripts are all merged into the script that includes them before the whole thing is processed as one. But if that is true, then test-forward.php should behave the same as test-together.php, but it is not. Instead, it appears that in test-forward.php, script2.php is not being read.

The code above is the full contents of the five files, so you should be able to reproduce this behavior on your system. I'm running PHP 7.2 under Windows 7.

Why is SayHello() not defined when running test-forward.php?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
174 views
Welcome To Ask or Share your Answers For Others

1 Answer

PHP checks the executet file for requried files and just add the content of the required file into the executet file. For Example if you execute script0.php which contains two required_once. It will first merge the content of both required_once into script0.php and then compile it.

So your executet file will be:

function1();
exit();
function function1() {}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...