【发布时间】:2012-11-06 05:30:44
【问题描述】:
我有一个用于构建字符串的预定义模式,应该在整个脚本中定期创建。
$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern
目前,我正在使用eval 根据最初定义的模式就地生成字符串。但是,由于这种情况偶尔会发生,并且eval 通常不好,我希望找到另一种方法。
请注意,模式在所有代码之上仅定义一次,我可以仅通过一行编辑所有脚本的模式。因此,任何更改都不应触及 $string 的原因。
我尝试了create_function,但需要相同数量的参数。使用eval,我可以轻松更改模式,但使用create-function,我需要更改整个脚本。例如,如果将字符串模式更改为
$str="$first @@ $second"; // One arg/var is dropped
评估示例:
$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("\$string = \"$str\";");
create_function 示例:
$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);
【问题讨论】:
-
你能举出
eval的例子吗?有点难以理解您到底要做什么,因为最后一个字符串声明看起来应该可以满足您的需求。 -
@Vulcan 我添加了示例来澄清问题。
-
谢谢,他们帮助澄清了你的问题,我已经回答了这个问题。
标签: php string function variables eval