drbouzlxb92333332 2015-02-17 00:57
浏览 100

可以在类方法中使用类名属性实例化PHP实例(在一行代码中)?

I would like to be able to instantiate a class using a class name stored in another class's property, and I want to do this with one line of code, as in the comments in the code below (and it should work on at least one recent version of PHP 5). Is this possible?

<?php

class Foo {

  public function doFoo() {

    echo "foo
";

  }

}

class Bar {

  function __construct($className) {

    $this->className = $className;

  }

  public function doBar() {

    //INSTEAD OF THESE TWO LINES...
    //$className = $this->className;
    //$instance = new $className();

    //I WOULD LIKE THIS (OR SOME OTHER) ONE-LINER TO WORK:
    $instance = $this->className();

    $instance->doFoo();

  }

}

$bar = new Bar('Foo');
$bar->doBar();

EXPECTED OUTPUT:

foo
  • 写回答

1条回答 默认 最新

  • duandian8110 2015-02-17 01:26
    关注

    There is an obvious typo in the code which is calling a function instead of a constructor, and can be fixed as follows:

    $instance = new $this->className();
    

    That does the trick.

    评论

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?