簡體   English   中英

使用stdClass的帶有可選參數的php函數

[英]php function with optional parameters using stdClass

假設我有一個函數,例如:[ $datastdClass() ]

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是帶有可選參數的函數。 但是,我收到一個錯誤: Object of class stdClass could not be converted to string

我假設您以以下形式調用了函數:

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

然后失敗,因為您最終進入else語句,並且無法將stdClass()連接到字符串(在本例中為“ World”)。

更多回顧表明,您實際的函數調用是test_3($data->name) ,並且$data->name可能是stdClass()而不是可以與“ World”連接的字符串。

作為參考,如果您遇到錯誤,請提供錯誤對應的實際行號。 我猜該錯誤是由於concat引起的,因為這是我看到將stdClass()轉換為字符串的唯一地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM