我甚至不知道这是否可行,但我正在尝试为现有对象设置一个可选值。
这是我正在尝试的代码的简化版本。
<?php
class configObject {
private $dataContainer = array();
public function set($dataKey, $dataValue) {
$this->dataContainer[$dataKey] = $dataValue;
return TRUE;
}
public function get($dataKey) {
return $this->dataContainer($dataKey);
}
$this->set('someValue', 'foobar');
} //End configObject Class
function getPaginationHTML($c = &$_config) {
$someOption = $c->get('someValue');
// Do other stuff
return $html;
}
$_config = new configObject();
$html = getPaginationHTML();
?>
我收到错误: 语法错误,意外'&amp;'在
任何帮助都表示赞赏,我不确定是否有可能做我正在尝试做的事情,对不起是一个菜鸟。
由于
答案 0 :(得分:1)
装饰器模式的示例:
class ConfigObject {
private $dataContainer = array();
public function set($dataKey, $dataValue) {
$this->dataContainer[$dataKey] = $dataValue;
return true;
}
public function get($dataKey) {
return $this->dataContainer[$dataKey];
}
}
class ConfigObjectDecorator {
private $_decorated;
public function __construct($pDecorated) {
$this->_decorated = $pDecorated;
}
public function getPaginationHTML($dataKey) {
$someOption = $this->get($dataKey);
// Do other stuff
$html = '<p>' . $someOption . '</p>';
return $html;
}
public function set($dataKey, $dataValue) {
return $this->_decorated->set($dataKey, $dataValue);
}
public function get($dataKey) {
return $this->_decorated->get($dataKey);
}
}
class ConfigFactory {
public static function create () {
$config = new ConfigObject();
return new ConfigObjectDecorator($config);
}
}
$config = ConfigFactory::create();
if ($config->set('mykey', 'myvalue'))
echo $config->getPaginationHTML('mykey');
请注意,可以轻松地重写ConfigFactory::create()
以添加参数以处理其他类型的装饰(或无)。