脚本在包含时是否自动执行


Are scripts automatically executed when they are included?

如果我有一个 php 脚本,并且我使用 "include" 关键字以便访问另一个脚本,那么我"包含"的脚本会自动执行吗?

Include 非常简单。它只包含文件,就好像代码就在那里一样。包括另一个文件就像复制内容并将其直接粘贴到包含它的文件中一样。

文件1.php

<?php
    echo "this is from file1";
?>

文件2.php

<?php
    include "file1.php";
    echo "this is from file2";
?>

这完全等同于:

<?php
    echo "this is from file1";
    echo "this is from file2";
?>

所以是的,包含的脚本确实会被执行 - 但不是单独执行的。它与包含文件中的代码合并,所有内容一起执行。

Include 的行为就像给定文件的内容被放置在那里一样。

如果您引用的文件仅包含classfunction定义,则显然不会执行它们。如果它们包含命令,则它们是。