我使用PHP创建了一个看起来像这样的函数
<?php
function addImage($imageFolder, $imageName) {
global $imageName;
$imageName = 'stackoverflow'.$imageName;
if (condition) {
global $imageFolder;
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return true;
}
}
}
if(addImage('image/', $imageName)){
echo $imageName;
echo $imageFolder;
}
?>
我面临的问题是,我可以在功能之外获得$imageName
但无法获得$imageFolder
(var_dump($imageFolder)
显示null
)。我是global variable
的新手,我真的不知道我是否正确使用它
答案 0 :(得分:2)
你走错了路。您已经拥有该函数之外的值。将它们分配给变量以重用它们。 global
用于访问在函数外部声明的变量。例如:
$myVariable = "hello";
function test() {
global $myVariable;
echo $myVariable;
}
test();
//output: hello
您可以在函数外部查看$ imageName,因为您在全局语句之后将其设置为值。但这确实不是正确的方法。
如果要修改传递的变量,请使用引用(http://php.net/manual/en/language.references.whatdo.php)
你应该这样做:
<?php
function addImage($imageFolder, &$imageName) {
$imageName = 'stackoverflow'.$imageName;
if (condition) {
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return true;
}
}
}
$imageFolder = 'image/';
$imageName = "..."; // don't know where this comes from in your code.
if(addImage($imageFolder, $imageName)){
echo $imageName;
echo $imageFolder;
}
答案 1 :(得分:2)
问题是global
关键字不会使现有变量成为全局变量。相反,它告诉PHP,当您通过该名称引用变量时,它应该在全局范围内查找。
您有两种方法可以解决此问题:
<?php
function addImage($imgFolder, $imgName) {
global $imageName;
$imageName = 'stackoverflow'.$imgName;
if (condition) {
global $imageFolder;
$imageFolder = $imgFolder;
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return true;
}
}
}
if(addImage('image/', $imageName)){
echo $imageName;
echo $imageFolder;
}
?>
$GLOBALS
变量<?php
function addImage($imageFolder, $imageName) {
$imageName = 'stackoverflow'.$imageName;
$GLOBALS['imageName'] = $imageName;
if (condition) {
$GLOBALS['imageFolder'] = $imageFolder;
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return true;
}
}
}
if(addImage('image/', $imageName)){
echo $imageName;
echo $imageFolder;
}
?>
<?php
function addImage($imageFolder, $imageName) {
$imageName = 'stackoverflow'.$imageName;
if (condition) {
$imagePath = $imageFolder.''.$imageName;
if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
return $imageName;
}
}
return false;
}
$imageFolder = 'image/';
if($imageName = addImage($imageFolder, $imageName)){
echo $imageName;
echo $imageFolder;
}
?>