php 语法 – local global
卡了我好久, 他妹的!
CREATE TABLE test.tes ( one varchar(20), two varchar(20), three varchar(20) );
function insert($table, $arr) { $link = new mysqli (‘localhost‘, ‘root‘, ‘‘, ‘test‘) or die (‘connnect‘.$link->error); $key = array_keys($arr); $key = join(‘,‘, $key); // echo $key, ‘<br>‘; $value = array_values($arr); $value = "‘".join("‘,‘", $value)."‘"; // echo $value, ‘<br>‘; $query = ‘insert into ‘.$table.‘ (‘.$key.‘) values (‘.$value.‘)‘; $link->query($query) or die (‘query fail: ‘.$link->error); } $arr = array(‘one‘=>‘1‘, ‘two‘=>‘2‘, ‘three‘=>‘3‘); insert(‘test‘, $arr);
把 link 放在外面, 一直插入失败……
<?php $link = new mysqli (‘localhost‘, ‘root‘, ‘‘, ‘test‘) or die (‘connnect‘.$link->error); function insert($table, $arr) { $key = array_keys($arr); $key = join(‘,‘, $key); // echo $key, ‘<br>‘; $value = array_values($arr); $value = "‘".join("‘,‘", $value)."‘"; // echo $value, ‘<br>‘; $query = ‘insert into ‘.$table.‘ (‘.$key.‘) values (‘.$value.‘)‘; $link->query($query) or die (‘query fail: ‘.$link->error); } $arr = array(‘one‘=>‘1‘, ‘two‘=>‘2‘, ‘three‘=>‘3‘); insert(‘test‘, $arr); ?>
现在成功了, 靠
<?php $link = new mysqli (‘localhost‘, ‘root‘, ‘‘, ‘test‘) or die (‘connnect‘.$link->error); function insert($table, $arr) { global $link; $key = array_keys($arr); $key = join(‘,‘, $key); // echo $key, ‘<br>‘; $value = array_values($arr); $value = "‘".join("‘,‘", $value)."‘"; // echo $value, ‘<br>‘; $query = ‘insert into ‘.$table.‘ (‘.$key.‘) values (‘.$value.‘)‘; $link->query($query) or die (‘query fail: ‘.$link->error); } $arr = array(‘one‘=>‘1‘, ‘two‘=>‘2‘, ‘three‘=>‘3‘); insert(‘test‘, $arr); ?>
总结, 函数里面, 要想引用外部的变量, 要先用 global $...
引入
$a = 3; function f() { global $a; // 没有 global 会出错 echo $a; } f();
function f() { global $a; $a = 3; } f(); echo $a; // 3