douou0977 2013-06-17 20:31
浏览 39
已采纳

带有可选参数的php函数使用stdClass

Suppose, I have a function such as: [$data is a stdClass()]

function test_1{
    ...
    ...
    if (somecondition){
        $data->name = NULL;
        test_2($data->name);
    }
    else{
        $data->name = 'hello';
        test_2($data->name);    
    }
    ...
    ...
}

function test_2($data){
    if (!empty($data->name)){
        test_3($data->name);
    }
    else{
        test_3();
    }
}

function test_3($s = ''){
    if (!empty($s)){
        //do something
    }
    else{
        $s .= 'World'; 
    }
}

test_3 is the function with optional parameters. However, I get an error: Object of class stdClass could not be converted to string

  • 写回答

1条回答 默认 最新

  • dpxpz37157 2013-06-17 20:36
    关注

    I'm assuming you called your function in a manner of the form:

    $data = new stdClass();
    test_3($data);
    

    This fails then as you end up in your else statement, and you can't concatenate a stdClass() to a string (in this case 'World').

    A bit more review suggests that your actual function call is test_3($data->name), and $data->name is likely of stdClass() instead of a string that can be concatenated with 'World'.

    For reference, if you have an error, it'd be helpful to provide the actual line number the error is corresponding to . . . I'm guessing the error is due to the concat, since that's the only place where I see a stdClass() to string conversion would be necessary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?