gpt4 book ai didi

php - 在文件 B 中包含文件 A,反之亦然

转载 作者:可可西里 更新时间:2023-11-01 00:50:11 25 4
gpt4 key购买 nike

“包含者”和“被包含者”在变量和函数作用域上有何不同?

例如,这两个测试的工作原理相同,但是否存在我应该了解的范围界定的微妙之处?

测试 1:

文件“one.php”:

<?php 
$a = 5;
include("two.php");
?>

文件“two.php:

<?php
function f($x) { return $x * 2; }
echo f($a);
?>

测试 2:

文件“one.php”:

<?php 
$a = 5;
?>

文件“two.php:

<?php
include("one.php");

function f($x) { return $x * 2; }

echo f($a);
?>

最佳答案

当您执行一个 PHP 文件时,它从全局范围开始。包含文档状态;

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

因为当您包含第二个文件时,您在两种情况下都处于全局范围内,变量范围将保持全局范围,并且包含的​​所有其他内容将始终具有全局范围。换句话说,两个文件和两种情况下的所有内容最终都在全局范围内,并且两者之间的范围界定没有区别。

关于php - 在文件 B 中包含文件 A,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9366563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com