Vale1976
Vale1976

Reputation: 31

Variable from a class to another class

I'm not very expert in PHP.

I have two classes in two different files.

class_Functions.php

<?php
class Functions {
    [...]
    public static function Get_Config($section,$key) {
        $config_file = 'config/config.ini';
        if (isset($config_data)) {
            unset($config_data);
        }
        $config_data = parse_ini_file($config_file, true, INI_SCANNER_RAW);
        return $config_data[$section][$key];
    }
    [...]
}
?>

class_PDO.php

<?php
Class Connection {

    private $server = "mysql:host=XXX;port=YYY;dbname=ZZZ";
    private $user = "AAA";
    private $pass = "BBB";
    private $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
    protected $con;

    public function openConnection() {
        try {
            $this->con = new PDO($this->server, $this->user,$this->pass,$this->options);
            return $this->con;
        } catch (PDOException $e) {
            return null;
        }
    }
    public function closeConnection() {
        $this->con = null;
    }
}
?>

I need to replace XXX, YYY, ZZZ, AAA and BBB in the second class with variables which values are as follow:

XXX -> $XXX = Functions::Get_Config('DB', 'host');

YYY -> $YYY = Functions::Get_Config('DB', 'port');

ZZZ -> $ZZZ = Functions::Get_Config('DB', 'db_name');

AAA -> $AAA = Functions::Get_Config('DB', 'username');

BBB -> $BBB = Functions::Get_Config('DB', 'password');

Upvotes: 1

Views: 39

Answers (1)

Vale1976
Vale1976

Reputation: 31

I've fix my problem editing the second class as follow:

Class Connection {
    protected $con;
    public function openConnection() {
        try {
            $this->server = "mysql:host=".Functions::Get_Config('DB','host').";port=".Functions::Get_Config('DB', 'port').";dbname=".Functions::Get_Config('DB', 'name');
            $this->user = Functions::Get_Config('DB', 'username');
            $this->pass = Functions::Get_Config('DB', 'password');
            $this->options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
            $this->con = new PDO($this->server, $this->user, $this->pass, $this->options);
            return $this->con;
        } catch (PDOException $e) {
            return null;
        }
    }
    public function closeConnection() {
        $this->con = null;
    }
}

Upvotes: 2

Related Questions