将数据传递给函数
好的,所以我知道这是非常基本的,我应该知道如何做到这一点,但我一片空白,无法在谷歌中找到答案。例如,我有一个包含变量数组的包含文件
$phrases["text"][1] = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
$phrases["mp3"][1] = "http://example.com/file.mp3";
,然后是一个获取变量的函数:
function return_phrase($phrase_name="", $fallback="",$default ="text"){
$next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
if(isset($tts_phrases[$default][$phrase_name])){
return $phrases[$default][$phrase_name]);
}
else if(isset($tts_phrases[$next][$phrase_name])){
return $phrases[$next][$phrase_name]);
}
else{
return $fallback;
}
}
问题是 $phrases
数组没有发送到该函数,我可以将该文件包含在函数本身,但我知道这是错误的方法。我想我需要使用 $global 只是不知道如何使用。
Okay So I know this is super basic and I should know how to do this but I'm blanking and having trouble finding the answer in Google. I have an include that has an array of variables for example
$phrases["text"][1] = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
$phrases["mp3"][1] = "http://example.com/file.mp3";
Then a function that gets the varibles:
function return_phrase($phrase_name="", $fallback="",$default ="text"){
$next= (isset($default) && $default =="mp3") ? 'text' : 'mp3';
if(isset($tts_phrases[$default][$phrase_name])){
return $phrases[$default][$phrase_name]);
}
else if(isset($tts_phrases[$next][$phrase_name])){
return $phrases[$next][$phrase_name]);
}
else{
return $fallback;
}
}
The problem is that the $phrases
arrays aren't being sent to the function I can include the file in the function itself but I know that's the wrong way to do it. I think I need to use $global just not sure how.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
方法 1:将 $phrases、$tts_phrases 作为参数传递
方法 2:使 $phrases、$tts_phrases 全局化(不好!)
使用全局变量是一个快速且简单的解决方案,但是一旦您的应用程序变得更大,它们就会变得很难跟踪。例如,以我在工作中必须处理的这个遗留代码片段为例:
每当我查看某个页面时,它只是凭空提取其中一个变量,我必须对整个项目按 Ctrl+F 并制作确保每一个小变化都不会弄乱整个应用程序。当您将变量保留在局部范围内时,您就可以确切地知道要更改的内容。
Method 1: Pass $phrases, $tts_phrases as parameters
Method 2: Make $phrases, $tts_phrases global (bad!)
Using global variables is a quick and easy fix, but once your application gets larger they become very hard to keep track of. For example, take this legacy code snippet that I have to deal with at work:
Any time I am looking at one of the pages that just pulls one of those variables out of thin air, I have to Ctrl+F the whole project and make sure that every little change hasn't messed up the whole app. When you keep your variables in local scope, you know exactly what you are changing.