[英]Create methods in a php class dynamically, so to have access to $this
I have a class that executes eval statements within a (very large) loop. 我有一个在(很大)循环内执行eval语句的类。 The eval statements are database stored code (mixed html & php) that needs to be processed. eval语句是需要处理的数据库存储代码(混合html和php)。 There is however is a serious performance issue because of this. 因此,存在一个严重的性能问题。
Instead of parsing the eval-statement every time in the loop, I would like to create a dynamic methods from the available eval-codes coming from the database within my class. 我不想在循环中每次都解析eval语句,而是想从类中数据库中可用的eval代码中创建动态方法。
I thought of the following pseudocode so that the eval code is converted to a method: 我想到了以下伪代码,以便将评估代码转换为方法:
class foo
{
private $test=3;
public function doloop()
{
for($i=0;$i<5;$i++)
{
$string="echo 50 * \$this->test.'<br>';";
$func="evalcode_001";
if(!isset(${$func}))
{
${$func}=create_function('',$string);
}
${$func}();
}
}
}
$obj_foo = new foo();
$obj_foo->doloop();//must output '150<br>150<br>150<br> .....'
However when running it I get the error message "Using $this when not in object context in ...". 但是,在运行它时,我收到错误消息“在...中不在对象上下文中时使用$ this”。 So obviously I didn't really create methods within the class. 因此,显然我并没有真正在类中创建方法。
So my question is: How do I create a method for a class dynamically and assign code for the given method. 所以我的问题是:如何动态为类创建方法并为给定方法分配代码。 Basically I want to be able to do: 基本上我希望能够做到:
$obj_foo->evalcode_001();
in the above example. 在上面的示例中。
Help appreciated 感谢帮助
PS I am using PHP5.4 PS我正在使用PHP5.4
If you can change $this->test
inside string (or write extra preg_match) you can use: 如果可以在字符串中更改$this->test
(或编写额外的preg_match),则可以使用:
<?php
class foo
{
public $test=3;
public $functions = array();
public function doloop()
{
for($i=0;$i<5;$i++)
{
$string="echo 50 * \$this->test.'<br>';";
$func="evalcode_001";
if(!isset($this->functions[$func]))
{
$string = str_replace('$this','$object', $string );
$this->functions[$func]= create_function('$object',$string);
}
$this->functions[$func]($this);
}
}
public function __call($name, $arguments) {
if (isset($this->functions[$name])) {
return $this->functions[$name]($this);
}
}
public function otherMethod() {
echo "test";
}
}
$obj_foo = new foo();
$obj_foo->doloop();//must output '150<br>150<br>150<br> .....
$obj_foo->evalcode_001();
$obj_foo->otherMethod();
However as other said I wouldn't like to use anything like that in my real script 但是正如其他人所说,我不想在我的真实脚本中使用类似的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.