首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在php中调用动态方法?

问如何在php中调用动态方法?
EN

Stack Overflow用户
提问于 2014-12-13 10:18:39
回答 3查看 198关注 0票数 0

我想用类似于以下代码的$property调用属性$method:

代码语言:javascript
复制
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行

我怎么才能修好它?

EN

回答 3

Stack Overflow用户

发布于 2014-12-13 10:26:34

为什么这么复杂?我觉得你更想找这样的东西。否则请让我多解释一下你想要什么:

代码语言:javascript
复制
<?php

    class test {
        public $property = 5;

        public function method() {
            return $this->property;
        }


    }

    $object = new test;
    echo $object->method();

?>

输出:

代码语言:javascript
复制
5
票数 0
EN

Stack Overflow用户

发布于 2014-12-13 10:51:23

这里有几个问题。您的方法名称字符串带有括号。因此,类似于字符串化方法的调用将无法工作。

假设您有$method = 'myMethod()';,如果您尝试$obj->$method();,它会对名为myMethod()()的未定义方法大喊大叫。如果将其保留为$obj->$method,则不会找到具有此名称的属性。

您最简单的解决方案是用一些预定义的逻辑从括号中去掉(因为以后可能需要参数,嗯?)

第一个解决办法..。只要移除它们.:

代码语言:javascript
复制
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。然后:

代码语言:javascript
复制
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 :)如果您确实需要从用户发送作为字符串发送的链式对象调用,那么编写您自己的字符串解析器是合理的(如上面的迷你版本)。

票数 0
EN

Stack Overflow用户

发布于 2014-12-13 10:27:54

尝尝这个

代码语言:javascript
复制
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);
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27457755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档