Foreach - loop through an object and change values ​​- php5

I have a simple wee cleanup function in PHP

It takes a value or an array of values ​​and does some clearing of the input. Now I use mysqli, which fetches strings 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 someone tell me how can I make an equivalent with an object as input?

+3
source share
3 answers

The function you are looking for is get_object_vars:

$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
    ///...
}

(foreach ($object as $key => $value)), . (stdClass ), ( Traversable...

Edit

... (__get __set, protected private), :

$newoutput = clone $input; //make a copy to return
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
    $newoutput->$outputname = htmlspecialchars(stripslashes($outputval));
}

- , 100% ... - (stdClass) :

$newoutput = new StdClass();
$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
    $newoutput->$outputname = htmlspecialchars(stripslashes($outputval));
}
+3

OP ircmaxell:

$vars = get_object_vars($input);
foreach ($vars as $outputname => $outputval) {
    $input->$outputname = htmlspecialchars(stripslashes($outputval));
}
0

, mysqli, , stdClass, ?

$newoutput = array()
foreach ((array) $output as $key => $value) {
  $newoutput[$key] = htmlspecialchars(stripslashes($value));
}

:

$output = (array) $output;
foreach ($output as &$value) {
  $value = htmlspecialchars(stripslashes($value));
}

, :

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;
}
0

Source: https://habr.com/ru/post/1779639/


All Articles