How to trim object properties in PHP?

2019-08-07 15:03发布

问题:

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.

回答1:

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);


回答2:

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);


回答3:

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.



标签: php oop object