How to trim object properties in PHP?

2019-08-07 14:36发布

I have an object $obj as

$obj->{' Property1'} = " value1";
$obj->{'Property2 '} = "value2 ";

I want to get this object $obj as

$obj->{'Property1'} = "value1";
$obj->{'Property2'} = "value2";

I am able to trim all the values using

foreach($obj as $prop => &$val)
{
     $val = trim($val);
}

but doing this (below) causing an error

foreach($obj as &$prop => &$val)
{
     $prop = trim($prop);
     $val = trim($val);
}

Please tell a solution. Thanks in advance.

标签: php oop object
3条回答
手持菜刀,她持情操
2楼-- · 2019-08-07 15:14

You can't reference a key.

What you have to do is unset it, and set the trimmed version like this:

<?php
$obj = new stdClass;
$obj->{' Property1'} = " value1";

foreach($obj as $prop => $val)
{
     unset($obj->{$prop});
     $obj->{trim($prop)} = trim($val);
}

var_dump($obj);
查看更多
戒情不戒烟
3楼-- · 2019-08-07 15:22

Because you're trying to trim the property of the object. You can't do that.

That would work for an array, but not for an object. If you need to alter the properties of an object you need to change the properties of the class.

查看更多
Bombasti
4楼-- · 2019-08-07 15:40

A little comment to Daan's answer. In his case script will fall into infinite loop if $obj have more than one property. So a working code looks like this.

<?php
$obj = new stdClass;
$obj->{' Property1'} = " value1";
$obj->{'Property2 '} = "value2 ";

$newObj = new stdClass;

foreach($obj as $prop => $val)
{
     $newObj->{trim($prop)} = trim($val);
}

$obj = $newObj;

unset($newObj);

var_dump($obj);
查看更多
登录 后发表回答