开发者

How to call a ".ini" file in a PHP Class?

开发者 https://www.devze.com 2023-02-07 13:15 出处:网络
I\'m building a Postgresql \"driver\" for a project. I have used an \".ini\" file to store the database details. Now I\'m a little bit confused on how to call the \".ini\" file.

I'm building a Postgresql "driver" for a project. I have used an ".ini" file to store the database details. Now I'm a little bit confused on how to call the ".ini" file.

I have this code. But give me an error.

<?php

class Postgresql {

    // Parse Config.ini
    $ini_array = parse_ini_file("../Config.ini", true);
    print_r($ini_array);

    public function __construct($hostname, $port, $username, $password, $database) {

        // Connection String
        $conn_string = "host=sheep port=5432 dbname=开发者_如何学运维test user=lamb password=bar";

        // Connect to Database
        $db_conn = pg_connect($conn_string);
    }
}

?>

What is the best place to put this lines of code?

// Parse Config.ini
$ini_array = parse_ini_file("../Config.ini", true);
print_r($ini_array);

Best Regards,


Well, you cannot put code in a class body like this:

class Foo {
   echo 'bar'; // Parse error
}

You have to put it either in a method, or before/after the class declaration. For your current issue, it would make a lot more sense to do:

class Postgresql {
    public function __construct($hostname, $port, $username, $password, $database) {

        // Connection String
        $conn_string = "host=sheep port=5432 dbname=test user=lamb password=bar";

        // Connect to Database
        $db_conn = pg_connect($conn_string);
    }
}

// Parse Config.ini
$ini_array = parse_ini_file("../Config.ini", true);

$postgres = new Postgresql(
    $ini_array['hostname'], $ini_array['port'], 
    $ini_array['username'], $ini_array['password'], 
    $ini_array['database']
);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号