我正在尝试从 mongo 获取网络设备模板配置并使用它来配置设备。所以我有一个 classDevice ,它具有与设备和 CRUD 方法相关的属性来操作设备。我的问题是我不知道如何扩展类属性。我尝试将属性放入$vars
withget_object_vars
但结果是相同的空变量。
这是我正在尝试做的一个例子:
<?php
class Device {
public $ip;
public $mode;
public function __construct($data = false)
{
$this->ip = $data['ip'];
$this->mode = $data['mode'];
}
public function configure(){
if ($this->mode == 'bridge'){
$localvar = 'test';
}
$template = array('0' => 'set ip $this->ip', '1' => 'set mode $this->mode', '2' => 'set calculated attr $localvar');
$cfgexpanded = array();
foreach ($template as $config) {
preg_match_all('/\$([a-zA-Z0-9\-\>]+)/', $config, $variables, PREG_PATTERN_ORDER);
foreach($variables[1] as $variable){
$config = str_replace('$'.$variable, $$variable, $config);
}
array_push($cfgexpanded, $config);
}
var_dump($cfgexpanded);
}
}
$data['ip'] = '1.2.3.4';
$data['mode'] = 'bridge';
$test = new Device($data);
$test->configure();
?>
这产生:
PHP Notice: Undefined variable: this->ip in /home/pedro/test.php on line 23
PHP Notice: Undefined variable: this->mode in /home/pedro/test.php on line 23
array(3) {
[0]=>
string(7) "set ip "
[1]=>
string(9) "set mode "
[2]=>
string(24) "set calculated attr test"
}
这是真正的代码,其中 $cfg 是 Mongo 返回的对象,其中包含要在我有局部变量和对象属性的地方应用的模板:
foreach ($cfg['cfg'] as $config) {
$$replace, $config));
preg_match_all('/\$([a-zA-Z0-9\-\>]+)/', $config, $variables, PREG_PATTERN_ORDER);
foreach($variables[1] as $variable){
$config = str_replace('$'.$variable, $$variable, $config);
}
array_push($cfgexpanded, $config);
}
因为如果有意义,您将搜索为$"this->ip"
字符串变量而不是对象$this->ip
。试试这个:
foreach($variables[1] as $variable){
$var = strpos($variable, '->') !== false ? $this->{end(explode('->', $variable))} : $$variable;
$config = str_replace('$'.$variable, $var, $config);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句