-1

我有一个类可以加载我的config.ini文件并将它们设置为对象/对象变量,我希望这些在类外部可读但不被更改?我怎样才能做到这一点?

配置文件

<?php

namespace app;

class config {

    public      $debug;
    private     $_data;

    public function __construct(){

        // parse config.ini
        $data = (object) json_decode(json_encode(parse_ini_file(BASE_PATH . DS . 'inc' . DS . 'app' . DS . 'config.ini', true)));

        // set debug
        $this->debug = (bool) $data->debug;

        // set data based on enviornment
        foreach($data->{$data->environment} as $key => $value){
            $this->_data->$key = (object) $value;
        }

        // turn on errors
        if($this->debug == 1){              
            error_reporting(E_ALL ^ E_NOTICE);
            ini_set("display_errors", 1);
        }

        // unset
        unset($data);

    }

    public function __get($name) {
        if (isset($this->_data->$name)) {
            return clone $this->_data->$name;
        } else {
            //
        }
    }

    public function __set($name, $value) {
        //
        echo 'ERROR';

    }


}
?>

应用程序.php

<?php
// load config
$config = new app\config(); 

echo '<pre>';
print_r($config);
echo '</pre>';

$config->database->server = 'test';

echo '<pre>';
print_r($config->database);
echo '</pre>';

$config->_data->database->server = 'test';

echo '<pre>';
print_r($config->database);
echo '</pre>';

?>

输出

    app\config Object
(
    [debug] => 1
    [_data:app\config:private] => stdClass Object
        (
            [database] => stdClass Object
                (
                    [server] => localhost
                    [database] => 
                    [username] => 
                    [password] => 
                )

        )

)

stdClass Object
(
    [server] => localhost
    [database] => 
    [username] => 
    [password] => 
)

stdClass Object
(
    [server] => localhost
    [database] => 
    [username] => 
    [password] => 
)

更新:我已经根据给出的评论更新了我的代码,但我遇到了两个问题......

1:__get如果我返回return $this->_data->$name;,我可以在课堂之外修改它......我通过添加解决了这个问题clone-return clone $this->_data->$name;

2:我现在不能设置或更新值 要么$config->database->server = 'test';但是$config->_data->database->server = 'test';...没有报告错误/异常,我什至尝试用什么都没有回显一些__set东西...

4

1 回答 1

2

成员必须是私人的。仅使用 get 函数来获取它们的值,但不能从类外部修改它们。例子:

class myClass{

     private $test;

     public function getTest()
     {   return $this->test;  }

}

它是如何称呼的:

$classTest = new myClass();

$classTest->test  NOT ALLOWED
$classTest->getTest()    -- Returns the  value
于 2013-11-01T21:14:34.090 回答