foreach - looping through object and changing values - php5
I have a simple wee cleansing function in PH开发者_如何学PythonP
It takes a value or array of values and does some input cleansing. Now I'm using mysqli which is fetching rows as objects so I need to be able to apply it to obejcts as well as arrays
function filter_out($output=''){
if($output != ''){
// i.e passed $_POST array
if(is_array($output)){
$newoutput = array();
foreach($output as $outputname=>$outputval){
$newoutput[$outputname] = stripslashes($outputval);
$newoutput[$outputname] = htmlspecialchars($newoutput[$outputname]);
}
} else if(is_object($input)){
?
}
}
}
Can anyone tell me how I can do the equivalent with object as input?
The function you're looking for is get_object_vars
:
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
///...
}
Don't try iterating on the object itself (foreach ($object as $key => $value)
), because it won't always work right. Sometimes it will (stdClass
as an example), and sometimes it won't (any class implementing Traversable
...
Edit
As far as your comment goes... As long as the classes aren't doing anything funny (__get
or __set
, protected
or private
), you could do:
$newoutput = clone $input; //make a copy to return
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
$newoutput->$outputname = htmlspecialchars(stripslashes($outputval));
}
But I can't really think of any method that will work 100% of the time... The other option, would be to return a nieve object (stdclass
) instead of the submitted one:
$newoutput = new StdClass();
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
$newoutput->$outputname = htmlspecialchars(stripslashes($outputval));
}
To answer the OP's comment on ircmaxell's answer:
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
$input->$outputname = htmlspecialchars(stripslashes($outputval));
}
Since you mention arrays and object coming from mysqli I'm guessing that they're just stdClass so why not just cast the object to an array?
$newoutput = array()
foreach ((array) $output as $key => $value) {
$newoutput[$key] = htmlspecialchars(stripslashes($value));
}
Or you could probably just do it in place:
$output = (array) $output;
foreach ($output as &$value) {
$value = htmlspecialchars(stripslashes($value));
}
So a single flow could look like:
function filter_out($output=''){
if($output != ''){
// i.e passed $_POST array
$is_array = is_array($output);
$output = (array) $output;
foreach($output as &$outputval){
$outputval = htmlspecialchars(stripslashes($outputval));
}
if (!$is_array) {
$output = (object) $output;
}
}
return $output;
}
精彩评论