Converting a variable to a function (automagically)

Discussion in 'PHP' started by Altari, Sep 22, 2011.

  1. #1
    I've seen this done before, by people far more skilled in the world of PHP than I am. So, hopefully someone here will know. =)

    I have a giant array of data that needs to be output on the page. Since I'm doing this a lot (the number of sites I work with is quite ridiculous), I want to have as few characters as possible cluttering up my code. And it could just be fun geek pr0n.

    Anyway, what I really want is simply 'title();' which will work like 'echo($array['title']);'
     
    Altari, Sep 22, 2011 IP
  2. Altari

    Altari Peon

    Messages:
    188
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I played around with it and found something that is non-optimal, but will work for now.

    	
    	foreach($itemArray AS $key => $value) {
    		if(is_array($value)) {
    			$$key = $value; // renames the array to the $key
    			continue;
    		}
    		$value	= addslashes($value);
    		$content	= "if(!\$echo) { return stripslashes('{$value}'); }
    						echo(stripslashes('{$value}'));";
    		$$key = create_function('$echo = true', $content);
    	}
    
    PHP:
    So, I can echo something by typing $variable() or just return the value with $variable(false). I'm still wide open for improvements and/or hacks that won't explode down the line. =) Thanks!
     
    Altari, Sep 22, 2011 IP