Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach - looping through object and changing values - php5

I have a simple wee cleansing function in PHP

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?

like image 352
gio Avatar asked Apr 28 '26 08:04

gio


2 Answers

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));
}
like image 116
ircmaxell Avatar answered Apr 29 '26 22:04

ircmaxell


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));
}
like image 45
Stefan Gehrig Avatar answered Apr 29 '26 20:04

Stefan Gehrig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!