首页 新闻 赞助 找找看

php和js的问题?

0
[已解决问题] 解决于 2013-08-19 18:33

php

 1 <?php
 2         function fn(){
 3             echo "inside the function:" .$var ."<br />";
 4             $var = "con 2";
 5             echo "inside the function:" .$var ."<br />";
 6         }
 7         $var = "con 1";
 8         fn();
 9         echo "outside the function:" .$var ."<br />";
10     ?>

js

1 function fn2(){
2         //因为dada已经存在fn2函数内部了。当它在函数内部找到这个变量之后就不往外找?
3         alert("inside the function:" + dada  +"<br />");
4         var dada = "con 2";
5         alert("inside the function:" + dada  +"<br />");
6     }
7     var dada = "con 1";
8     fn2();
9     alert("outside the function:" + dada  +"<br />");

 

如上两个代码片段,

php输出:

inside the function:
inside the function:con 2
outside the function:con 1

js输出:

inside the function:undefined
inside the function:con 2
outside the function:con 1

 

但是如果把红色的代码删除了,

php输出:

inside the function:
outside the function:con 1
js输出:

inside the function:con 1
outside the function:con 1

分析:

js代码中看到dada 后就在fn中找有没有定义,看到有定义了,所以就不往上面找?

但是因为定义在使用下面,所以值还是空。

删除了fn内部定义的变量后,因为在fn中没有找到dada的定义所以往外找,找到了所以为1?

php是怎么回事?

问题补充:

<?php
function fn(){
global $var1;
$var1 = "con 2";
echo "inside the function:" .$var1 ."<br />";

/* echo "inside the function:" .$var ."<br />";*/
}

fn();
echo "outside the function:" .$var1 ."<br />";
?>

 

如果在函数内部定义一个全局变量,那函数内部和外部都可以访问。

但是如果在函数外面定义,那函数还是访问不到?

 

 

<?php
$var1 = 4;
function fn($var1){
$var1 = $var1 +1 ;
echo "inside the function:" .$var1 ."<br />";

/* echo "inside the function:" .$var ."<br />";*/
}
fn($var1);
echo "outside the function:" .$var1 ."<br />";
?>

 

================================

global $var1;
$var1 = 4;
function fn(){

echo "inside the function:" .$var1 ."<br />";
}
fn();
echo "outside the function:" .$var1 ."<br />";

snowinmay的主页 snowinmay | 菜鸟二级 | 园豆:240
提问于:2013-07-25 12:27
< >
分享
最佳答案
0

JS和PHP的变量是不同的,PHP内部和外部变量无法公用,除非使用Global或者引入等方法。

JS的话函数内部可以访问函数外部的变量,但是外部无法访问函数内部的变量。

奖励园豆:5
Add On JavaScript | 菜鸟二级 |园豆:217 | 2013-07-25 14:06
其他回答(1)
0

可以使用

function fn(){
global $var1;

......

 

或者

function fn(&$var1){
.....

河边的老牛 | 园豆:214 (菜鸟二级) | 2013-08-08 10:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册