PHP: Dynamic Variables
Okay so it's been a bloody long time since I posted, but I have been brain bleeding busy at work and my girlfriend has joined me in Cape Town, so my free time mostly consists of spending it with my gf, friends or relaxing.
Anyway just a quick post on naming of variables.
If you want to make it easier for designers to create a page, but you want to hide the complexities of the php from them, then you could quite possibly use the operator $$. A quick example code before I explain:
$variableName = "myVar"; $data = "Here is some data"; $$variableName = $data; echo $myVar;
This will output
Here is some data;
By simply using the $$ operator, we are telling PHP we want to create a variable with the name that is stored in the current variable. So in our case $variableName has the string "myVar" stored in it. Hence it creates a variable called $myVar. So by doing this:
$$variableName = $data;
We are actually doing this:
$myVar = $data;
Well lets say you have written a very nice little DB lib that does all the nasty stuff for your programmers. So on a particular page load it would load up any number of variables from the DB. So now instead of your designers having to deal with knowing how arrays work, you can simply provide them with a bunch of variables that they need to embedd in their page layout. So they could effectively create simple HTML pages that look like this.
<html> <head> <title><?=$title;?></title> </head> <body> <div id="header"> <?=$header;?> </div> <div id="content"> <?=$content;?> </div> <div id="footer"> <?=$footer;?> </div> </body> </html>
This is way more friendlier to designers you can concentrate on the layout and HTML coding and not have to worry about coding bits of PHP code. Then in an include file you could have the php code that builds the variables.
<? $sql = "SELECT page.title, general.header, page.content, general.footer FROM pageSpecific as 'page', generalCode as 'general' WHERE page.id = {$pageId} and general.siteID = {$siteID}"; $result = mysql_query($sql, $dbConn); if ($result) { $row = mysql_fetch_assoc($result); foreach($row as $key => $value) $$key = $value; } ?>
This will build 4 variables, $title, $header, $content, $footer.
As you can see it's not very complex, but the results can really help seperate the page design from the page coding, without having to use a proper template engine like Smarty or some other one.
I'm sure you'll all find more useful ways of using this sort of code.
Syn

Recent comments
18 weeks 4 days ago
36 weeks 5 days ago
36 weeks 5 days ago
38 weeks 2 days ago
45 weeks 2 days ago
2 years 11 weeks ago
2 years 12 weeks ago
2 years 12 weeks ago
2 years 12 weeks ago
2 years 12 weeks ago