Writing to static classes in PHP
Assuming I have a Config class that I use to access the config开发者_开发百科 vars from everywhere (Config::X
).
Is it possible to implement a function that can be called from outside the class that adds and/or modifies properties?
Something like this is what I'm thinking of:
class Config
{
const myVar = 'blah';
public static function write( $name, $value )
{
//....
}
}
echo Config::myVar; // Clear
Config::write( 'test', 'foo' );
echo Config::test; // Should be foo
I've seen something similiar in CakePHP but couldn't figure out the solution. My goal would be being able to write to the base Config class from different files, e.g.: store Database information in a separate file.
You can't achieve this without declaring the variables first unless you ditch static variables and use concrete implementations instead. Even if you do declare the variables first you will have to call them using `$:
class Config {
const $myVar = 'blah';
public static $test;
public static function write( $name, $value )
{
//....
}
}
Config::write( 'test', 'foo' );
echo Config::$test; // Will be foo
If you have a concrete implementation then you can leverage __get and __set so you don't have to declare all your variables.
class Config {
const $myVar = 'blah';
private $vars = array();
public function __set($name, $value) {
$this->vars[$name] = $value;
}
public function __get($name) {
if(isset($this->vars[$name])
return $this->vars[$name];
return null;
}
}
echo Config::myVar; // Still the same
$config = new Config();
$config->test = 'foo';
echo $config->test; // Will be foo
This will mean you'll need to pass around your config object if you need it somewhere. If you find this annoying you might want to look into dependency injection.
You can't modify values of a static class. If you would like to have this functionality, you'll need to make an instance of the class,and store in it session if you need the values to persist over pages.
Your code seems to make the write function bind up a new const called $name .... never seen that done before.
精彩评论