为了账号安全,请及时绑定邮箱和手机立即绑定

php里面如何跨文件访问变量?

php里面如何跨文件访问变量?

PHP
神不在的星期二 2019-03-15 11:10:06
比如我的a.php的内容为:<?php$DbServer = '192.168.1.106:1265';$User = 'wx';$Password = 'wx123456';?>然后在我的b.php里面有一个方法为:function CreateConn(){$con = mysql_connect($DbServer, $User, $Password);if (!$con)die('Could not connect: ' . mysql_error());mysql_select_db("wenxibiz_wxstock", $con);return $con;}会报错说:Notice: Undefined variable: DbServer in C:\xampp\htdocs\wx\Utilities\GenConn.php on line 6Notice: Undefined variable: User in C:\xampp\htdocs\wx\Utilities\GenConn.php on line 6Notice: Undefined variable: Password in C:\xampp\htdocs\wx\Utilities\GenConn.php on line 6请问这个是怎么回事,该如何解决呢?
查看完整描述

2 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

你这个是涉及到全局变量问题,有几种方法

首先,肯定要引入a文件

include 'a.php'

 

一、global

1

2

3

4

5

6

7

8

$str = 'hello';

function test()

{

    global $str;

    echo $str;

    echo $GLOBAL['str'];//这两个效果一样

}

test();//输出 hello

二、define定义全局变量

1

2

3

4

5

6

define('STR','hello');

function test()

{

    echo STR;

}

test();//输出hello

 注意,这个STR前面不要$


 


查看完整回答
反对 回复 2019-03-20
  • 2 回答
  • 0 关注
  • 1563 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信