Home > Backend Development > PHP Tutorial > 小白求指点:自定义函数内调用另外一个函数里的全局变量,该怎么写啊

小白求指点:自定义函数内调用另外一个函数里的全局变量,该怎么写啊

WBOY
Release: 2016-06-23 13:34:16
Original
950 people have browsed it

member.inc.php:

function marrbase(){if(isset($_COOKIE["uname"]) && isset($_COOKIE["uid"])){global $mbase;$mbase_data = mysql_query("select * from dh_member where `id`=" . $_COOKIE["uid"] . " and `mck`=1");if (!$mbase_data){die(mysql_error());exit();}$mbase = mysql_fetch_array($mbase_data);}else{exit();}}
Copy after login


我是这样写的:
require_once("member.inc.php");function supp(){marrbase();echo $mbase["email"]; exit();}
Copy after login


输出为空,小白求大神指点一下这个该怎么写才规范正确啊..


回复讨论(解决方案)

function supp() {
global $mbase;
marrbase();
echo $mbase["email"]; exit();
}

function supp() {
global $mbase;
marrbase();
echo $mbase["email"]; exit();
}





谢谢啊,我还是有个小疑问:

我现在是在supp()里面调用的,但是我在其他页面输出的时候 直接echo $mbase["email"]; exit(); 又能输出值
这是怎么回事啊?

因为你在函数里有 global $mbase;
所以 $mbase 就是全局变量了
只要你执行过 marrbase 函数
$mbase 就可在函数外访问了

但这样的写法并不符合软件工程学中 低耦合 的要求

因为你在函数里有 global $mbase;
所以 $mbase 就是全局变量了
只要你执行过 marrbase 函数
$mbase 就可在函数外访问了

但这样的写法并不符合软件工程学中 低耦合 的要求



那该怎么写 才正规啊

作为参数传递

作为参数传递?

怎么设计啊

function marrbase(){  ....  return $mbase;}function supp() {  $mbase = marrbase();  echo $mbase["email"];}
Copy after login
Copy after login


function marrbase(&$mbase){  ....  $mbase = ....;}function supp() {  marrbase($mbase);  echo $mbase["email"];}
Copy after login
Copy after login

function marrbase(){  ....  return $mbase;}function supp() {  $mbase = marrbase();  echo $mbase["email"];}
Copy after login
Copy after login


function marrbase(&$mbase){  ....  $mbase = ....;}function supp() {  marrbase($mbase);  echo $mbase["email"];}
Copy after login
Copy after login



非常感谢~~受教了 谢谢
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template