如何将PHP文件中的变量加载到包含类的另一个PHP文件中

时间:2015-03-06 20:34:54

标签: php

考虑以下情况:

我有一个名为'config.php'的php文件,如下所示:

<?PHP
$dbIp = "<databseip>";
$dbUte = "<databaseuser>";
$dbPass = "<databasepassword>";
$dbDbase = "<databasename>";
$dbPort = "3636";
?>

另一个名为'player.php'的php文件如下:

<?PHP

include 'config.php';

class Player {

/* PDO Object */
private $cn;

function __construct() {
    $this->prepareDatabase();
}

private function prepareDatabase() {
    $dbms = 'mysql';

    $dsn = "$dbms:host=$dbIp;port=$dbPort;dbname=$dbDbase"; //HERE I CANNOT GET VARIABLES FROM 'config.php'
    $this->cn=new PDO($dsn, $dbUte, $dbPass); //AND HERE TOO xD
    $this->cn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}

由于某种原因,我无法从播放器类访问config.php中的变量。显然我不明白。有人能解释我获取这些变量的正确方法吗?

1 个答案:

答案 0 :(得分:2)

它们的范围不同。要使用变量,必须将其添加为参数:

<?php

class Player {

/* PDO Object */
private $cn;

function __construct($dbIp, $dbPort, $dbDbase) {
    // Here you pass the parameters to the prepareDatabase method
    $this->prepareDatabase($dbIp, $dbPort, $dbDbase);
}

private function prepareDatabase($dbIp, $dbPort, $dbDbase) {
    $dbms = 'mysql';

    $dsn = "$dbms:host=$dbIp;port=$dbPort;dbname=$dbDbase"; //HERE I CANNOT GET VARIABLES FROM 'config.php'
    $this->cn=new PDO($dsn, $dbUte, $dbPass); //AND HERE TOO xD
    $this->cn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}

include 'config.php';

// Here you pass the parameters to the constructor
$player = new Player($dbIp, $dbPort, $dbDbase);