如何从不同的文件访问函数内的变量?

时间:2016-01-25 10:28:10

标签: php mysql pdo

我有两个文件,一个functions.php,它包含一个连接数据库的PDO对象,包含作为变量的列和一个index.php,用于输出包含数据的变量。数据库连接工作但是当我尝试从我的函数回显变量时,它返回undefined,我做错了什么;

的functions.php

<? php 

function connectDB() {
    $hostname = 'xxxxxxxx';
    $db = 'xxxxxxx';
    $user = 'xxxxxxxx';
    $pass = 'xxxxxxx';

    $dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); 

    $sql = "//my query";

    $query = $dbh->prepare($sql);
    $query->execute(array('//value','//value'));            
    $query->setFetchMode(PDO::FETCH_ASSOC);

    while ($r = $query->fetch()):

        $var1 = $r['column1']; 
        $var2 = $r['column2'];
        $var3 = $r['column3'];
        $var4 = $r['column4'];
        $var5 = $r['column5'];

    endwhile;                                                       

}

?>

的index.php

<?php
include 'functions.php';

?>

<?php 

try {

connectDB();
echo 'You are connected to Database';
echo $var1;
$dbh = null; 

    }
catch(PDOException $e) { 
        echo $e -> getMessage(); 
    }

?>

3 个答案:

答案 0 :(得分:2)

这些变量默认是connectDB()函数的本地变量,因此您必须事先在全局范围内声明它们,或者使用$ GLOBALS来设置它们:

方法1

public static object GetProperty(this object instance, string name)
    {
        if (instance == null)
            throw new ArgumentNullException("instance");

        if (name == null)
            throw new ArgumentNullException("name");

        Type type = instance.GetType();
        PropertyInfo property = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);

        if (property == null)
            throw new InvalidOperationException(string.Format("Type {0} does not have a property {1}", type, name));

        object result = property.GetValue(instance, null);

        return result;
    }

方法2

<? php 

    $var1 = ''; 
    $var2 = '';
    $var3 = '';
    $var4 = '';
    $var5 = '';

function connectDB() {
    $hostname = 'xxxxxxxx';
    $db = 'xxxxxxx';
    $user = 'xxxxxxxx';
    $pass = 'xxxxxxx';

    $dbh = new PDO("mysql:host=$hostname; dbname=$db; charset=utf8", $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); 

    $sql = "//my query";

    $query = $dbh->prepare($sql);
    $query->execute(array('//value','//value'));            
    $query->setFetchMode(PDO::FETCH_ASSOC);

    while ($r = $query->fetch()):

        $var1 = $r['column1']; 
        $var2 = $r['column2'];
        $var3 = $r['column3'];
        $var4 = $r['column4'];
        $var5 = $r['column5'];

    endwhile;                                                       

}

?>

此致,您的复制粘贴服务:)

答案 1 :(得分:1)

通常可以通过两种方式之一访问变量,或者作为传递给函数的参数,或者通过在函数内声明变量为全局变量。希望以下有所帮助

function banana( $externalvar=false ){
   echo $externalvar;
}

or

function banana(){
    global $externalvar;

    echo $externalvar;
}

答案 2 :(得分:0)

智能代码应使用yield keyword

function connectDB() {
    // ...
    $output = [];
    $index  = 0;
    while ($r = $query->fetch()):
        yield $r;
    endwhile; 
}

然后:

foreach ($connectDB() as $row)
    echo $row['column1'], PHP_EOL;
    echo $row['column2'], PHP_EOL;
    echo $row['column3'], PHP_EOL;
endforeach;

否则,只需返回一个数组,然后extract

function connectDB() {
    // ...
    $output = [];
    $index  = 0;
    while ($r = $query->fetch()):
        ++$index;
        foreach($r as $key => $value) {
            $output[$name . '_' . $index] = $value;
        }
    endwhile; 
    return $output; 
}

然后:

$vars = connectDB();
extract($vars);
;
echo $column1_1, PHP_EOL;
echo $column2_1, PHP_EOL;
echo $column3_1, PHP_EOL;
;
echo $column1_2, PHP_EOL;
echo $column2_2, PHP_EOL;
echo $column3_2, PHP_EOL;

第二个目的非常难看。