dqh1992 2013-08-28 12:32
浏览 16
已采纳

如何将一组变量传递给一个类

This may be a bit of an XY questions, so I'm going to explain what I'm trying to do first. I'm attempting to create a single php file to handle all of my page refresh AJAX calls. That means I want to be able to send it a class name, plus a list of the variables that the class constructor takes, and for it to then create the class.

I can create the class fine. $class = new $className(); works just fine for creating the class. The problem is passing in the default variables. Most of the variables are objects containing other classes, so I can't just include this once the class is created, I need to pass them as the class is created.

I was thinking something along the lines of:

$varStr = '';
$s = '';
foreach($vars as $var) {
    switch($var['type']) {
        case 'object':
            $varStr .= $s . '$' . $var['value'];
            break;
        case 'variable':
            $varStr .= $s . $var['value'];
    }
    $s = ',';
}
$class = new $className(echo $varStr);

Now obviously echo $varStr isn't going to work there, but I have no idea what will. Is there anything I can do that will output the variables from my array into the class constructor like that? Is what I'm trying to do even possible? Is there a better way?

Whilst I understand I could just pass the whole array to the class constructor, this would complicate the main part of the program, and I would rather just ditch the idea of a single page for AJAX refresh than go down that route.

  • 写回答

2条回答 默认 最新

  • dongpa5277 2013-08-28 13:06
    关注

    This is a wild guess at what you're trying to do but maybe this is what you're after:

    // Generate constructor args
    
    $args = array();
    foreach($vars as $var) {
        switch($var['type']) {
            $value = $var['value'];
            case 'object':
                args[] = ${$value};     // evaluate, I think that's what you want?
                break;
            case 'variable':
                args[] = $value;        // use as is
                break;
        }
    
    }
    
    // Instanciate class with args
    $class = new ReflectionClass($className);
    $obj = $class->newInstanceArgs($args);
    

    For this to work, it would require $vars to enumerates args in the correct order expected by each class constructor.

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

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算