JV’s Power Tips for PHP (1) - Accessing Other Variables from Within this Type of Template
(Page 5 of 7 )
Of course not all PHP variables come in the form of $basic_var. So how can we access more complex variables such as associative arrays, objects, cookies and variables submitted by forms within our templates? Here’s how:
Variables posted via a forms Simply wrap the standard variable access syntax within {}’s like so:
<html>
<head>
<title>Simple Template</title>
</head>
<body>
{$_POST[‘var_from_form’]}
</body>
</html> This works for associative arrays as well...actually this works anywhere in PHP. For example instead of this:
<?php
$turkey_speach = “Hello “ . $_POST[‘turkey_name’] . ” how are you?”;
echo $turkey_speach;
?> You can do this and save yourself breaking the “’s:
<?php
$turkey_speach = “Hello {$_POST[‘turkey_name’]} how are you?”;
echo $turkey_speach;
?> It also works here:
<?php
$turkey = array (“lover”=>”me”,”in_person” =>”dustin”);
print “Page by {$turkey[‘lover’]}<p>”;
print <<<END
Hello {$turkey[‘in_person’]} how are you?<br>
“OK?”
END;
?> Object syntax works too:
<html>
<head>
<title>Simple Template</title>
</head>
<body>
$object_name->var_name
</body>
</html> You can also use object syntax within PHP print statements (and while assigning variables). I prefer using objects to arrays for this type of thing and often create objects on the fly to use in templates and dynamic output. Here’s how:
<?php
// Create an object on the fly..
$output->{‘my_turkey’} = “Gobble”;
$output ->{‘my_dog’} = “Rex”;
$turkey_buffer = “Page by: $output->my_turkey:<p>”;
echo $turkey_buffer;
print <<<END
Hello $output->my_dog how are you?<br>
“OK?”
END;
?>Next: Using Objects to Store Multiple Output Values >>
More PHP Articles
More By Justin Vincent