Jump to content

[SOLVED] Recurse through classes properties?


phpzone

Recommended Posts

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");

		}

	} 

               ...
               ...
               ...

 

 

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

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.