如何在PHP类中使用外部变量?

时间:2012-03-19 23:01:01

标签: php class variables

我有config.php这个......

$dbhost = "localhost";

我希望能够在类中使用$ dbhost变量。

User.class.php

include 'config.php';    
class User {
    private $dbhost = ???
    }

还有其他几个这样的问题,但是它们用于其他一些特定的用途,我想这只是一个基本的东西,我在网上找不到任何其他的东西。

更新:哇,感谢所有人的帮助。这个网站的新用户,但我可能只是坚持下去并尽可能地回馈。

4 个答案:

答案 0 :(得分:4)

您可以使用global variable,定义constant会更好,但最好使用setter / getter方法。当您使用类时,应将其使用的任何外部资源传递给它。如果你想进一步研究它,这个设计模式称为dependency injection

在这个例子中,我将setter和getter合并为一个单独的方法,并且包括使用构造函数在第一次创建实例时设置值的能力:

class User
{
    private $host = null;

    public function host($newHost = null)
    {
        if($newHost === null)
        {
            return $this->host;
        }
        else
        {
            $this->host = $newHost;
        }
    }

    function __construct($newHost = null)
    {
        if($newHost !== null)
        {
            $this->host($newHost);
        }
    }
}

//Create an instance of User with no default host.
$user = new User();

//This will echo a blank line because the host was never set and is null.
echo '$user->host: "'.$user->host()."\"<br>\n";

//Set the host to "localhost".
$user->host('localhost');

//This will echo the current value of "localhost".
echo '$user->host: "'.$user->host()."\"<br>\n";

//Create a second instance of User with a default host of "dbserver.com".
$user2 = new User('dbserver.com');

//This will echo the current value of "dbserver.com".
echo '$user2->host: "'.$user2->host()."\"<br>\n";

答案 1 :(得分:2)

对于像db主机这样的东西,使用常量:

// define it first
define('DBHOST', 'localhost');

// then anywhere you can use DBHOST:
class User {
    function __construct() {
        echo DBHOST;
    }
}

http://php.net/manual/en/language.constants.php

答案 2 :(得分:1)

我认为有几种方式。 首先将它传递给类构造函数:

include 'config.php';    
class User {         
    private $dbhost;

    function __construct($dbhost){
      $this->dbhost=$dbhost;
    }
}
$user= new User($dbhost);

或使用二传手:

include 'config.php';    
class User {         
    private $dbhost;

    function setDbhost($dbhost){
      $this->dbhost=$dbhost;
    }
}
$user= new User();
$user->setDbhost($dbhost);

或使用CONSTANTS:

define('DBHOST', 'localhost');
class User {         
    private $dbhost;

    function __construct(){
      $this->dbhost=DBHOST;
    }
}

或使用global:

include 'config.php';    
class User {         
    private $dbhost;

    public function __construct() {
    global $dbhost;
    $this->dbhost=$dbhost;
}
}

答案 3 :(得分:0)

如果您打算使用变量(而不是常量),请使用以下代码。

在config.php中

$dbhost = "localhost";

在User.class.php中

include 'config.php';    
class User {
    global $dbhost;
}