dongyan7172 2016-08-25 03:07
浏览 27
已采纳

PHP是否允许在stdObject中包含重复的属性?

I'm stuck with a very weird bug. I have an object called $row that looks like this:

stdClass Object
(
    [title] => Some Title
    [body] => My body
    [topic] => Topic
    [dataType] => Survey
    [csvrownum] => 1
)

I'm just trying to print out the title property in the following way:

print_r($row->title);

However for some reason that doesn't output anything.

Then I've tried to manually set the title property and print it right after, something like this:

$row->title = 'My Title';
print_r($row->title);

Surprisingly it worked but why? To make this more strange I decided to var_dump the object after set the title variable by hand:

$row->title = 'My Title';
var_dump($row);

And this is what I've got:

class stdClass#391 (6) {
  public $title =>
  string(3) "Some title"
  public $body =>
  string(7) "My body"
  public $topic =>
  string(6) "Topic"
  public $dataType =>
  string(17) "Survey"
  public $csvrownum =>
  int(1)
  public $title =>
  string(8) "My title"
}

Notice the title key is duplicated with different values. Is there any condition under this could happen?

  • 写回答

1条回答 默认 最新

  • dongzhaiqiang6108 2016-08-25 03:22
    关注

    No, PHP does not allow an object to have duplicate property names, because objects in PHP are implemented just like arrays. They are both implemented as ordered hashmaps. In a hashmap, two things that have the same hash, overwrite each other.

    You likely just have unprintible characters in your object property name. You can see this more clearly by doing something like the following for debug purposes...

    foreach($row as $key => $value) {
        var_dump($key);
    }
    

    If we had an object like this, for example, you'd see it gets overwritten.

    $row = new stdClass;
    $row->title = "First";
    $row->title = "Second";
    

    But something like this might be more deceptive...

    $row = new stdClass;
    $row->{"title\0"} = "First";
    $row->title = "Second";
    

    Output from the foreach using var_dump on the key, would reveal this...

    string(6) "title"
    string(5) "title"
    

    Notice one is string of length 6 and the other is a string of length 5.

    Grain of salt

    It's always better to use var_dump when attempting to debug variables than using something like print_r, as var_dump was specifically designed for debug purposes, whereas print_r is just a recursive print (hence the name). Printing values like null, false, or empty strings, gives you no useful information for debug purposes, but var_dump does.

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

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题