在实例创建时调用对象的方法 [英] calling a method of an object at instance creation

查看:142
本文介绍了在实例创建时调用对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中为什么不能这样做:

In PHP why can't I do:

class C
{
   function foo() {}
}

new C()->foo();

但我必须这样做:

$v = new C();
$v->foo();

在所有语言中我都可以做到...

In all languages I can do that...

推荐答案

在PHP中,您不能在像new Foo()->someMethod();

In PHP, you can't call an arbitrary method on a freshly created object like new Foo()->someMethod();

对不起,就是这样.

但是您可以像这样构建工作:

But you could build a work around like this:

<?php
class CustomConstructor
{
  public static function customConstruct($methodName)
  {
    $obj = new static; //only available in PHP 5.3 or later
    call_user_method($methodName, $obj);
    return $obj;
  }
}

像这样扩展CustomContructor:

Extend CustomContructor like this:

class YourClass extends CustomConstructor
{
  public function someCoolMethod()
  {
    //cool stuff
  }
}

并像这样实例化它们:

$foo = YourClass::customConstruct('someCoolMethod');

我还没有测试过,但是这个或类似的东西应该可以工作.

I have not tested it but this or something like it should work.

更正:仅在PHP 5.3和更高版本中有效,因为需要后期静态绑定.

这篇关于在实例创建时调用对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆