PHP: magic methods

Regarding __toString


class my_tag_A{

	public $id='';
	public $href='';
	public $target='';
	public $class='';
	
	public $label='';
	
	function __construct($href, $label){
		$this->href = $href;
		$this->label = $label;
	}
	
	public function __toString(){
		return 'nz_arr(
			array('id', 'href', 'target', 'class')) . ' >' 
			. $this->label . '';
	}
	
	function nz_arr($attrib_arr){
		$s = '';
		foreach($attrib_arr as $attrib){
			$s .= $this->nz($attrib);
		}
		return $s;
	}

	/**
	 * Print the tag attribute if it is not blank, such as id="$this->id"
	 * @param string $attrib
	 * @return string
	 */
	function nz($attrib){
		$s = '';
		if($this->$attrib != '') $s = $attrib .' = "' . $this->$attrib . '"';
		return $s;
	}

	//This causes RECURSION because of parsing between double quotes.
	//This is a very UNEXPECTED behaviour!
	function nz_($attrib){
		$s = '';
		if($this->$attrib != '') $s = "$attrib = \"$this->$attrib\"";
		return $s;
	}
	
}//end  class

//usage
$a = new my_tag_A('abc.php', 'ABC'); $a->target = '_blank';
echo $a;
//prints:
//    ABC

Leave a Reply