我在projectRoot/conf/
下创建了一个简单的.ini文件,其中包含以下内容:
[db]
name="db_name"
usr="someone"
pass="a_definitely_secure_pass"
host="some_host"
如果我在projectRoot/index.php
中这样称呼:
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT']. '/conf/site.ini', true);
echo '<pre>'. print_r($ini,1) .'</pre>';
然后我得到了我的阵列:
Array
(
[db] => Array
(
[name] => db_name
[usr] => someone
[pass] => a_definitely_secure_pass
[host] => some_host
)
)
但是,如果我尝试对类执行此操作,则将得到NULL输出。这是我的基本控制器类:
<?php
namespace App\Core;
class Controller
{
protected $ini;
public function __construct()
{
$this->ini = false;
if (file_exists($_SERVER['DOCUMENT_ROOT']. '/conf/site.ini')) {
$this->ini = parse_ini_file($_SERVER['DOCUMENT_ROOT']. '/conf/site.ini', true);
}
}
}
我扩展了一个通用的(最小的)数据库类:
<?php
namespace App\Core;
class Connection extends Controller
{
protected $conn;
protected $qry;
protected $stmt;
public function __construct()
{
var_dump($this->ini); # this shows as NULL
# this all fatal error's as it can't seem to parse the ini file correctly
$this->conn = new \PDO(
'mysql:host='. $this->ini['db']['host'] .';dbname='. $this->ini['db']['name'],
$this->ini['db']['usr'],
$this->ini['db']['pass']
);
$this->stmt = false;
$this->qry = '';
parent::__construct();
}
# etc
这又会在我的index.php
页面上被调用(以及解析文件的测试):
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(-1);
require_once $_SERVER['DOCUMENT_ROOT']. '/vendor/autoload.php';
# this works
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT']. '/conf/site.ini', true);
echo '<pre>'. print_r($ini,1) .'</pre>';
# trying to do it like this causes the fatal error
$conn = new \App\Core\Connection();
$conn->select(['*'], 'orders')
->join('order_items', 'order_id', 'orders', 'order_id', 1)
->where('total', 'lt')
->execute([5]);
echo '<pre>'. print_r($conn->fetchAll(), 1) .'</pre>';
这让我想,这里可能存在范围问题-但将其从protected
变量更改为public
无效。
为什么不能使用类设置/获取.ini conf值?