duanhe3393 2012-04-04 10:06
浏览 62
已采纳

显示对象的所有公共属性(名称和值)

This thread didn't helped me.

If I use

$class_vars = get_class_vars(get_class($this));

foreach ($class_vars as $name => $value) {
    echo "$name : $value
";
}

I get

attrib1_name : attrib2_name : attrib3_name

There are no values. Also a private attribute is shown, which I don't want.

If I use

echo "<pre>";
print_r(get_object_vars($this));
echo "</pre>";

I get

Array ( [atrrib1_name] => attrib1_value [attrib2_name] => attrib2_value )

Here again I have a private attribute and all sub attributes. But this time I have the values. How can I constrain this to one level?

Isn't there a possibility to show all public attributes with their values of an object?

  • 写回答

4条回答 默认 最新

  • douxie2029 2012-04-04 10:12
    关注

    You are seeing non-public properties because get_class_vars works according to current scope. Since you are using $this your code is inside the class, so the non-public properties are accessible from the current scope. The same goes for get_object_vars which is probably a better choice here.

    In any case, a good solution would be to move the code that retrieves the property values out of the class.

    If you do not want to create a free function for that (why? seriously, reconsider!), you can use a trick that involves an anonymous function:

    $getter = function($obj) { return get_object_vars($obj); };
    $class_vars = $getter($this);
    

    See it in action.

    Update: Since you are in PHP < 5.3.0, you can use this equivalent code:

    $getter = create_function('$obj', 'return get_object_vars($obj);');
    $class_vars = $getter($this);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c