phpzone Posted June 6, 2008 Share Posted June 6, 2008 Hi everyone, I have the following class and I'm wanting to know, is it possible to recurse through the properties that are defined to apply a function just as htmlspecialchars to them, so I don't have to use the function separately on each. I know I could just have the properties in an array instead and recurse the array, but I wondered if there was actually a way I could just recurse through properties? class Blog_User { private $user_id = 0; private $user_fullname = ''; private $user_username = ''; private $user_password = ''; private $user_email = ''; private $user_groupid = 0; private $user_enabled = ''; private $user_lastlogin = 0; private $errors = ''; public function __construct() {} public function __destruct() {} public function __get( $name ) { if ( isset( $this->$name ) ) { return $this->$name; } else { throw new Exception("Unknown property: $name"); } } ... ... ... Link to comment https://forums.phpfreaks.com/topic/108967-solved-recurse-through-classes-properties/ Share on other sites More sharing options...
RMcLeod Posted June 6, 2008 Share Posted June 6, 2008 You can recurse through an objects properties using foreach, however this only works for public properties. You can however create a class method that does this for you. <?php class Blog_User { private $user_id = 0; private $user_fullname = ''; private $user_username = ''; private $user_password = ''; private $user_email = ''; private $user_groupid = 0; private $user_enabled = ''; private $user_lastlogin = 0; private $errors = ''; public function iterate() { foreach($this as $var => $value) { $this->$var = htmlspecialchars($value); } } ?> Link to comment https://forums.phpfreaks.com/topic/108967-solved-recurse-through-classes-properties/#findComment-559024 Share on other sites More sharing options...
phpzone Posted June 6, 2008 Author Share Posted June 6, 2008 Ah, great, thanks. You know I never thought to just iterate over $this, usually I do put the variables in a private array. Thanks for the advice! Link to comment https://forums.phpfreaks.com/topic/108967-solved-recurse-through-classes-properties/#findComment-559058 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.