foreach - 循环对象并更改值 - php5
我在 PHP 中有一个简单的小便清理函数,
它接受一个值或值数组并进行一些输入清理。现在我正在使用 mysqli,它将行作为对象获取,因此我需要能够将其应用于对象以及数组
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)){
?
}
}
}
有人能告诉我如何使用对象作为输入来执行相同的操作吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您要查找的函数是
get_object_vars
:
不要尝试迭代对象本身(
foreach ($object as $key => $value)
),因为它并不总是能正常工作。有时会(例如stdClass
),有时不会(任何实现Traversable
...编辑
就您的评论而言...只要类没有执行任何有趣的事情(
__get
或__set
、protected
或private
),你可以这样做:但我真的不能想想任何能够 100% 成功的方法...另一种选择是返回一个 nieve 对象 (
stdclass
) 而不是提交的对象:The function you're looking for is
get_object_vars
: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 implementingTraversable
...Edit
As far as your comment goes... As long as the classes aren't doing anything funny (
__get
or__set
,protected
orprivate
), you could do: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:回答OP对ircmaxell的回答的评论:
To answer the OP's comment on ircmaxell's answer:
既然你提到来自 mysqli 的数组和对象,我猜测它们只是 stdClass,那么为什么不将对象转换为数组呢?
或者您可以就地执行:
因此单个流程可能如下所示:
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?
Or you could probably just do it in place:
So a single flow could look like: