Jump to content

PHP class - passing options as an array


nath2099

Recommended Posts

Hi, I decided today to try and figure out why I'd use a class instead of just functions.

 

In order to get the basics of how to write and use a class I have written this:

 

class picOutline
{
function picOutline($imageUrl="",$borderColor = "#ffffff",$link="",$altText="",$width="",$height="", $align="left") {
	$this->imageUrl=$imageUrl;
	$this->borderColor=$borderColor;
	$this->link=$link;
	$this->altText=$altText;
	$this->width=$width;
	$this->height=$height;
	$this->align=$align;

}
Function Set($varname,$value) {
	$this->$varname=$value;
}
Function displayImage() {
	if ($this->link) { echo "<a href='".$this->link."'>"; }

	echo "<img src='".$this->imageUrl."' ";
	if ($this->borderColor) { echo "style='border: 1px solid ".$this->borderColor.";' "; }
	if ($this->width) { echo "width='".$this->width."' "; }
	if ($this->height) { echo "height='".$this->height."' "; }
	if ($this->altText) { echo "alt='".$this->altText."' "; }
	echo "align='".$this->align."' />";
	if ($this->link) { echo "</a>"; }
}

}

 

and created an instance of this class:

 

				$image = new picOutline();
				$image->imageUrl = "images/flags/".$country.".gif";
				$image->displayImage();

 

my question is.. is it possible to do something like:

var options= array("imageUrl" => "/path/to/image", "borderColor" => "#ffffff", "width" => "100");
$image = new picOutline(options);
$image->displayImage();

??

Link to comment
https://forums.phpfreaks.com/topic/242828-php-class-passing-options-as-an-array/
Share on other sites

class picOutline
{
function picOutline($opts=array()) {
	$this->imageUrl=$opts['imageUrl'];
	$this->borderColor=$opts['$borderColor'];
	$this->link=$opts['$link'];
	$this->altText=$opts['$altText'];
	$this->width=$opts['$width'];
	$this->height=$opts['$height'];
	$this->align=$opts['$align'];

}
Function Set($varname,$value) {
	$this->$varname=$value;
}
Function displayImage() {
	if ($this->link) { echo "<a href='".$this->link."'>"; }

	echo "<img src='".$this->imageUrl."' ";
	if ($this->borderColor) { echo "style='border: 1px solid ".$this->borderColor.";' "; }
	if ($this->width) { echo "width='".$this->width."' "; }
	if ($this->height) { echo "height='".$this->height."' "; }
	if ($this->altText) { echo "alt='".$this->altText."' "; }
	echo "align='".$this->align."' />";
	if ($this->link) { echo "</a>"; }
}

}

HTH

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.