How to use external variable in PHP class?
I have a config.php with this ...
$dbhost = "localhost";
I want to be able to use the $ dbhost variable inside the class.
User.class.php
include 'config.php';
class User {
private $dbhost = ???
}
There are a few more such questions, but they were for some other specific uses, and I guess this is just a basic thing that I can't find anything else on the internet for.
UPDATE: Wow, thanks for helping everyone. New to this site, but I could just stick and go back where I can.
source to share
several ways i think. First, pass it to the class constructor:
include 'config.php';
class User {
private $dbhost;
function __construct($dbhost){
$this->dbhost=$dbhost;
}
}
$user= new User($dbhost);
Or use a setter:
include 'config.php';
class User {
private $dbhost;
function setDbhost($dbhost){
$this->dbhost=$dbhost;
}
}
$user= new User();
$user->setDbhost($dbhost);
Or using CONSTANTS:
define('DBHOST', 'localhost');
class User {
private $dbhost;
function __construct(){
$this->dbhost=DBHOST;
}
}
OR with global:
include 'config.php';
class User {
private $dbhost;
public function __construct() {
global $dbhost;
$this->dbhost=$dbhost;
}
}
source to share
You can use a global variable defining a constant would be better, but the best is to use the setter / getter method. When you use a class, any external resource it uses must be passed to it. This patter project is called Dependency Injection if you want to explore further.
In this example, I have combined setter and getter into one method and enabled the ability to set the value on first instantiation using the constructor:
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";
source to share