我想用类似于以下代码的$property调用属性$method:
class test
{
public $property= 5;
public function method()
{
return $this;
}
}
$text = 'method().property';
$array = explode('.', $text);
$tt = implode('->', $array);
$object = new test;
echo $object->$tt;但此错误返回:
注意:未定义的属性: test::$method()->property中的/var/www/html/test2.php,位于第16行
我怎么才能修好它?
发布于 2014-12-13 10:26:34
为什么这么复杂?我觉得你更想找这样的东西。否则请让我多解释一下你想要什么:
<?php
class test {
public $property = 5;
public function method() {
return $this->property;
}
}
$object = new test;
echo $object->method();
?>输出:
5发布于 2014-12-13 10:51:23
这里有几个问题。您的方法名称字符串带有括号。因此,类似于字符串化方法的调用将无法工作。
假设您有$method = 'myMethod()';,如果您尝试$obj->$method();,它会对名为myMethod()()的未定义方法大喊大叫。如果将其保留为$obj->$method,则不会找到具有此名称的属性。
您最简单的解决方案是用一些预定义的逻辑从括号中去掉(因为以后可能需要参数,嗯?)
第一个解决办法..。只要移除它们.:
class test
{
public $property= 5;
public function method()
{
return $this;
}
}
$text = 'method().property';
$array = explode('.', $text);
$array[0] = str_replace("()", "", $array[0]);
$test = new test();
echo $test->$array[0]()->$array[1];这里的输出是5。
但是,我想您可能会期望用户method(arg1, arg2).property。然后:
class test
{
public $property= 5;
public function method($a, $b)
{
$argsProduct = $a*$b;
$this->property += $argsProduct;
return $this;
}
}
$text = 'method(2, 6).property';
$array = explode('.', $text);
$array[0] = str_replace(["(", ")", ","], " ", $array[0]);
$array[0] = preg_split("/\\s+/", $array[0]);
$args = array_slice($array[0], 1, count($array[0])-1, true);
$test = new test();
echo call_user_func_array(array($test, $array[0][0]), $args)->$array[1];输出:17; // 2 * 6 = 12; 12 + 5 = 17
当然,可能有更好的解决办法来提取论点,但我现在还没有想到这一点。需要知道的是,您需要知道用户可以将其作为字符串发送给您的预定义结构。而且,必须避免使用EVAL :)如果您确实需要从用户发送作为字符串发送的链式对象调用,那么编写您自己的字符串解析器是合理的(如上面的迷你版本)。
发布于 2014-12-13 10:27:54
尝尝这个
class test
{
public $property= 5;
public function method()
{
return $this->property;
}
}
$object = new test;
$text = $object->method();
$array = explode('.', $text);
$tt = implode('->', $array);
print_r($tt);https://stackoverflow.com/questions/27457755
复制相似问题