php 类 stdClass 的对象无法转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9758185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Object of class stdClass could not be converted to string
提问by Tomas Smith
I dont know why but I get this error :
我不知道为什么,但我收到此错误:
Catchable fatal error: Object of class stdClass could not be converted to string
可捕获的致命错误:无法将类 stdClass 的对象转换为字符串
For this code:
对于此代码:
$sql = "SELECT * FROM player ORDER BY score DESC LIMIT $begin";
$arr = array();
while($obj = mysql_fetch_object(mysql_query($sql))) {
//$arr[] = $obj;
echo $obj;
}
回答by jmlnik
You're using mysql_fetch_object
(which returns an object) and then trying to output it as a string. That won't work.
您正在使用mysql_fetch_object
(返回一个对象),然后尝试将其作为字符串输出。那行不通。
In your case, you should use a function that is capable of printing the contents of the object. There are many but the most straight-forward ones are print_r
or var_dump
. if you're outputting in an HTML context, you might wan to wrap a <pre>
tag around the output to make it more readable or click "View source" in your browser.
在您的情况下,您应该使用能够打印对象内容的函数。有很多,但最直接的是print_r
或var_dump
。如果您在 HTML 上下文中输出,您可能希望<pre>
在输出周围包裹一个标签以使其更具可读性,或者在浏览器中单击“查看源代码”。
If you're writing your own objects, they can also be "converted" to strings by implementing the __toString()
magic method
如果您正在编写自己的对象,也可以通过实现魔术方法将它们“转换”为字符串__toString()
Also, as people have said in the comments, your code will run the query on each pass through the loop. Check out the documentation hereand read the examples.
此外,正如人们在评论中所说,您的代码将在每次通过循环时运行查询。查看此处的文档并阅读示例。
Note: You might have simplified the example for SO's sake, but make sure to sanitize your variables (e.g. $begin
) to avoid SQL injections!
注意:为了 SO,您可能已经简化了示例,但请确保清理您的变量(例如$begin
)以避免 SQL 注入!
回答by Dor Shemer
Use print_r
or var_dump
instead of echo
使用print_r
或var_dump
代替echo