如何让类变量可读但保护它们不被更改?

时间:2013-11-01 20:43:52

标签: php

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

的config.php

<?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';

    }


}
?>

app.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';设置或更新值但是...没有报告错误/异常,我甚至尝试用{{1没什么......

1 个答案:

答案 0 :(得分:2)

会员需要保密。仅使用get函数来获取它们的值,但不能从类外部修改它们。例如:

class myClass{

     private $test;

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

}

如何调用:

$classTest = new myClass();

$classTest->test  NOT ALLOWED
$classTest->getTest()    -- Returns the  value