在 first.php 文件中,我分配了一些变量并定义了一些常量值,
define("CONSTANT1", "cons1value");
$variable1 = "var1value";
$variable2 = array(
"key1" => "value1",
"key2" => "value2"
);
我需要通过 second.php 文件更改值。这种变化可能像:
define("CONSTANT1", "cons1value_updated");
$variable1 = "var1value_updated";
$variable2 = array(
"key1" => "value1_updated",
"key2" => "value2",
"key_3_added" => "value3_added"
);
我想使用 Nikic PhpParser 来完成这项工作。我试过这段代码 -
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$prettyPrinter = new PhpParser\PrettyPrinter\Standard;
$traverser = new PhpParser\NodeTraverser;
$source = file_get_contents("first.php");
try {
$stmts = $parser->parse($source);
$stmts = $traverser->traverse($stmts);
} catch (Error $error) {
echo "Parse error: {$error->getMessage()}\n";
return;
}
foreach ($stmts as $item) {
if (property_exists($item, "expr")) {
$Ex = $item->expr;
if (property_exists($Ex, "var")) {
if ($Ex->var->name == 'variable2') {
foreach ($Ex->expr->items as $fetItem) {
switch ($fetItem->key->value) {
case 'key1':
$fetItem->value->name->parts[0] = "value1_updated";
break;
case 'key2':
$fetItem->value->name->parts[0] = "value2_updated";
break;
}
}
$Ex->expr->items[] = [
"key3_added" => "value3_added"
];
}
}
}
}
一切正常。但在该部分,
$Ex->expr->items[] = [
"key3_added" => "value3_added"
];
我收到一个错误。有什么解决办法吗?