2016-01-13 135 views
0

的index.phpPHP变量传递给函数在另一个文件

require '../include/FunctionFile.php'; 
$test = "blah"; 
myfunction($test); 

FunctionFile.php

function myfunction($test){ 
    global $test; 
    echo $test; 
} 

我想通过$test值给myFunction,但看起来它不工作,它什么也没有返回,没有任何错误日志。

+0

是你的'myfunction'类的一部分吗?或只是简单的书面功能 – urfusion

+0

@urfusion不,这是一个简单的功能 – Pedram

+1

你确定带有功能的文件被正确包含吗? – RamRaider

回答

2

您的功能需要return值。

的index.php

require '../include/FunctionFile.php'; 
$test = "blah"; 
$var=myfunction($test);// assign to vaiable 
echo $var; 

FunctionFile.php

function myfunction($test){ 
    return $test;// use return type here 
} 
+0

不工作 – Pedram

+0

使用它来检查页面ini_set('display_errors',1)中的错误; ini_set('display_startup_errors',1); error_reporting(E_ALL);' – Saty

+0

为prev回复道歉!这是我的错,它工作得很好..谢谢 – Pedram

0

你也可以试试这个

myfunction("args"); 
 
function myfunction($test){ 
 
\t echo $test; 
 
}

1

我知道其他队友已经提供了解决方案,所以我在未来方面加我的答案。

假设你有两个功能getHello()getGoodbye()具有不同定义的相同目的。

// function one 
function getHello(){ 
    return "Hello"; 
} 

// function two 
function getGoodbye(){ 
    echo "Goodbye"; 
} 

//now call getHello() function 
$helloVar = getHello(); 

结果:

'Hello' // return 'hello' and stored value in $helloVar 

//now call getGoodbye() function 
$goodbyeVar = getGoodbye(); 

结果:

'Goodbye' // echo 'Goodbye' and not stored in $goodbyeVar 

echo $helloVar; // "Hello" 
echo $goodbyeVar; // Goodbye 

结果:

'GoodbyeHello' 

// now try same example with this: 

echo $helloVar; // "Hello" 
//echo $goodbyeVar; // Goodbye 

结果应该相同,因为getGoodbye()已经是echo'ed的结果。

现在实例与您的代码:

function myfunction($test){ 
    //global $test; 
    echo $test; 
} 

function myfunction2($test){ 
    //global $test; 
    return $test; 
} 

myfunction('test'); // test 
myfunction2('test'); // noting 

//You need to echo myfunction2() as i mentioned in above. 

echo myfunction2('test'); // test 

为什么它不是在你的代码?:

工作,你需要像指派值之前声明变量Global

global $test; 
$test = "blah"; 
相关问题