【问题标题】:PHP equivalent of send and getattr?PHP 相当于 send 和 getattr?
【发布时间】:2009-04-21 04:29:23
【问题描述】:

如果 Ruby 被邀请参加派对并带来:

foobarobject.send('foomethod') 

.. 和 Python 被邀请参加同一个聚会并带来:

getattr(foobarobject, 'foomethod')()

.. PHP 必须为聚会带来什么?

附赠问题:如果 Ruby 和 Python 嫉妒 PHP 的派对青睐,他们会在 PHP 的文档中搜索哪些英文术语以便在 PHP 背后谈论它?

【问题讨论】:

  • 两者不同:Ruby版本调用方法; Python 版本返回绑定方法。
  • +1 以创造性的方式表达问题:)
  • @Miles:现在通过在 python 版本中添加 paren 来修改问题。

标签: php oop reflection equivalent getattr


【解决方案1】:

PHP 带来了这个:

$foobarobject->{"foomethod"}();

...还有可乐和薯条。

编辑

虽然上面的术语是variable variables,但手册中并没有专门讨论对对象执行此操作。但是,您可以使用 call_user_func 实现相同的目的:

call_user_func(array($foobarobject, "foomethod"));

【讨论】:

    【解决方案2】:

    使用变量来保存方法名。与 Paolo 的第一个示例几乎相同,但除非您知道,否则可能不那么明显。

    $method = "foomethod";
    $foobarobject->$method();
    

    您还收到了Reflection classes

    $method = new ReflectionMethod('Foobar', 'foomethod');
    $method->invoke(null);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-21
      • 2013-05-22
      • 2016-01-01
      • 2012-12-03
      • 2011-08-27
      • 2012-04-23
      • 2012-03-11
      • 2010-11-28
      相关资源
      最近更新 更多