Skip to content

PHP: Iterate through object members

May 24, 2012

I was doing some work on a small project of mine in PHP and decided their must be a more efficient way to sanitize all string members of an object.  Previously, my old method was a blunt procedural style similar to something that would be seen in C.

public function escape($link) {
	$this->name = mysql_real_escape_string($name, $link);
	$this->description = mysql_real_escape_string($description, $link);
	$this->address = mysql_real_escape_string($address, $link);

And so forth for every object that would be passed to and from the database.  I’ve been studying up on Ruby and in doing so learned to take a few different angles to coding.  It turns out PHP supports “duck-typing” functionality similar to that in Ruby. Due to the way PHP handles objects and arrays with such similarity, I thought perhaps it would be possible to iterate through members of an object. While I’m not much too exposed to paradigms outside of the traditional object-oriented style and procedural style, a bit of thinking outside my traditional box helped me realize how simple a more graceful solution would be (also note  the new version is using a mysqli object for the connection instead of the mysql_ set).

public function escape($link) {
	foreach($this as $member => $value) {
		if(is_string($value)) {
			$this->{$member} = $link->real_escape_string($value);
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: