doulu4203 2014-06-28 08:41
浏览 22
已采纳

如何通过从字符串创建类将参数传递给类

My question title may be logically wrong, because I do not know how to explain it :)

Here are example of what I need. I have master classe and two another classes which this masters class creates. This two classes have constructors with parameters and I do not know how to pass this parameters.

class Master {

    function __construct() {
        $this->setup_settings();
        $this->load_classes();
    }

    public function setup_settings() {
        $this->settings['classes'] = array( 'Class_A', 'Class_B' );
    }

    public function load_classes() {
        foreach( $this->settings['classes'] as $class) {
            new $class; //Here are problem!
        }
    }

}

class Class_A {

    function __construct( $setiings ) {
        $this->settings = $settings;
    }

}
class Class_B {

    function __construct( $setiings ) {
        $this->settings = $settings;
    }

}

In this case I have an error:

Warning: Missing argument 1 for Class_A ::__construct()

I understanding why it is. But how to pass parameters to this class in this way (when class names are in array)? When I am creating string and passing it I have an error: class cant be converted to string.

  • 写回答

3条回答 默认 最新

  • dongpu1315 2014-06-28 08:47
    关注

    You forgot the arguments in parens ($args).

    $instance = new $objectName($args);
    

    ClassA and ClassB both have constructors that expect a parameter called $settings. BTW, you misspelled it there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏