如何在我的函数中写常量?

时间:2015-05-15 04:14:11

标签: php function constants

function insert_data($array){
    $dbh=new PDO('sqlite:C:\test.sqlite');
    $sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
    $q = $dbh->prepare($sql);
    $q->execute($array);
    $dbh=null;
}  

我想将C:\test.sqlite定义为常量。

define('db_name','C:\test.sqlite');

但是我不能在我的函数insert_data中使用常量。

function insert_data($array){
    $dbh=new PDO("sqlite:db_name");
    $sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
    $q = $dbh->prepare($sql);
    $q->execute($array);
    $dbh=null;
} 

发生错误:

Fatal error: Call to a member function execute() on a non-object in....

我不想把这个函数写成格式:

 function insert_data($array,$db){
    $dbh=new PDO("sqlite:{$db}");
    $sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
    $q = $dbh->prepare($sql);
    $q->execute($array);
    $dbh=null;
} 

如何解决?

1 个答案:

答案 0 :(得分:0)

定义变量 - $db = 'C:\test.sqlite';

并将其global

function insert_data($array){
    global $db;
    $dbh=new PDO("sqlite:{$db}");
    $sql = "INSERT INTO quote (symbol,price) VALUES (?,?)";
    $q = $dbh->prepare($sql);
    $q->execute($array);
    $dbh=null;
} 

Read it here