【问题标题】:php function with optional parameters using stdClass使用 stdClass 的带有可选参数的 php 函数
【发布时间】:2013-06-13 22:13:24
【问题描述】:

假设,我有一个函数,例如:[$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 是带有可选参数的函数。 但是,我收到一个错误:Object of class stdClass could not be converted to string

【问题讨论】:

  • test_1 缺少参数,因此此代码甚至无法编译。我怀疑您在此处转录时进行了其他更改,因此我们看不到真正的问题。
  • @Barmar:在这个问题中添加/不添加参数并不重要。问题是关于test_3。无论如何,我已经编辑了代码。希望你现在能弄清楚。 ;)
  • 你没有修复test_1,它仍然缺少参数列表。如果test_1 不重要,为什么要包含它?
  • 这里有些东西没有意义。你调用test_2($data->name),所以test_2 的参数$data 是一个字符串,而不是一个对象。但是随后test_2() 使用了$data->name,这应该会失败,因为$data 不是此函数中的对象。

标签: php function parameter-passing stdclass


【解决方案1】:

我假设您以以下形式调用您的函数:

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

这会失败,因为您最终会使用 else 语句,并且您无法将 stdClass() 连接到字符串(在本例中为“世界”)。

更多评论表明您的实际函数调用是 test_3($data->name),而 $data->name 可能是 stdClass() 而不是可以与“世界”连接的字符串。

作为参考,如果您有错误,提供错误对应的实际行号会很有帮助。 . .我猜这个错误是由 concat 引起的,因为这是我看到 stdClass() 到字符串转换的唯一地方。

【讨论】:

  • test_1() 中,$data->name 设置为NULL 或字符串。那怎么可能是stdClass
  • @Barmar 这似乎很明显,这主要是模板代码,这也是为什么当我第一次回答时,我假设问题出在使用 stdClass 对象作为参数调用 test_3() . . .
  • 愚蠢的我,当问题显示如何调用 test_3() 时,我认为这与问题有关。
猜你喜欢
  • 2011-04-28
  • 1970-01-01
  • 2019-02-06
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
相关资源
最近更新 更多