Php 访问函数中的全局变量
我有第一个php文件,其中包含一些在函数外部定义的变量。我试图找到一种在函数的第二个php文件中使用这些变量的方法。因为我读到不建议使用全局关键字,所以我尝试根据这里的一个答案通过一个变量作为参数作为测试,但没有成功。下面是我目前代码的简化版本: Vars.php具有:Php 访问函数中的全局变量,php,wordpress,global-variables,Php,Wordpress,Global Variables,我有第一个php文件,其中包含一些在函数外部定义的变量。我试图找到一种在函数的第二个php文件中使用这些变量的方法。因为我读到不建议使用全局关键字,所以我尝试根据这里的一个答案通过一个变量作为参数作为测试,但没有成功。下面是我目前代码的简化版本: Vars.php具有: $test = 'test'; include 'Vars.php'; function add_content($test){ echo 'This is a '. $test; } add_action( 'wo
$test = 'test';
include 'Vars.php';
function add_content($test){
echo 'This is a '. $test;
}
add_action( 'woocommerce_single_product_summary', 'add_content', 15 );
Functions.php与:
$test = 'test';
include 'Vars.php';
function add_content($test){
echo 'This is a '. $test;
}
add_action( 'woocommerce_single_product_summary', 'add_content', 15 );
我不确定这是否重要,但正如你所看到的,这是一个wordpress网站。如果有人知道如何做到这一点,我们将不胜感激。如果必须在函数本身中重新定义所有变量,这将是多余的。@Adrien希望您希望访问函数内部的变量,这些变量位于函数外部,以便您可以使用
$GLOBALS
它是一个超全局变量,包含当前脚本文件中所有变量的引用($GLOBALS
将变量名存储为键,变量值存储为键值的数组)
因此,请尝试以下方法:
Vars.php
$test = 'test';
Function.php
<?php
include 'test.php';
function add_content(){
echo 'This is a '. $GLOBALS["test"]; //$test variable store in this with the variable name test as key and value of the variable as value of key
}
add_content( 'woocommerce_single_product_summary', 'add_content');
您的问题是什么?global$test;函数add_content()…
为什么不使用globals?@Adrien如果您想访问函数的外部变量,那么为什么要传递该变量?函数add_content($test){
$test将被15覆盖谢谢你的回答。正如我在问题中所说的,我读到不建议使用$globals,这就是为什么我不愿意使用它,但我看不到任何其他解决方法。我测试了你的脚本,它工作正常。再次感谢:)