Access a global variable in a PHP function(在 PHP 函数中访问全局变量)
问题描述
根据大多数编程语言的作用域规则,我可以访问在函数内部定义的变量,但为什么这段代码不起作用?
According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn't this code work?
<?php
    $data = 'My data';
    function menugen() {
        echo "[" . $data . "]";
    }
    menugen();
?>
输出为[].
推荐答案
这是一个范围问题.简而言之,应该避免使用全局变量所以:
It's a matter of scope. In short, global variables should be avoided so:
您要么需要将其作为参数传递:
You either need to pass it as a parameter:
$data = 'My data';
function menugen($data)
{
    echo $data;
}
或者把它放在一个类中并访问它
Or have it in a class and access it
class MyClass
{
    private $data = "";
    function menugen()
    {
        echo this->data;
    }
}
另请参阅@MatteoTassinari 答案,因为您可以将其标记为全局以访问它,但通常不需要全局变量,因此重新考虑您的编码是明智的.
See @MatteoTassinari answer as well, as you can mark it as global to access it, but global variables are generally not required, so it would be wise to re-think your coding.
这篇关于在 PHP 函数中访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHP 函数中访问全局变量
				
        
 
            
        基础教程推荐
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
 - php中的foreach复选框POST 2021-01-01
 - php中的PDF导出 2022-01-01
 - 将变量从树枝传递给 js 2022-01-01
 - 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
 - PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
 - 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
 - Yii2 - 在运行时设置邮件传输参数 2022-01-01
 - php 7.4 在写入变量中的 Twig 问题 2022-01-01
 - Web 服务器如何处理请求? 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				