note 106046 added to functions.anonymous
| From: | lennymail at nospam dot gmail dot com | Date: | Wed, 05 Oct 2011 17:40:56 +0000 |
| Subject: | note 106046 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-183648@lists.php.net to get a copy of this message | ||
A practical example of anonymous functions could be a clean template system. Here you can completely
remove messy HTML from your code and keep everything very readable. The last statement that prints
the HTML in the example below resembles LISP or other functional type languages. The closure retains
the HTML tag from parent scope(which can be initialized in creative ways) and properly closes it
after the function call. Items can either nested or composed within HTML tags.
You can take this idea further and "map and wrap" columns and rows of recordsets with HTML
for display. All that is missing now is the CSS to make it attractive in the browser.
Closures can be thought of as a very primitive class that has one "apply" method with some
private and public data. Functional programming has been around since the first programming
languages in the 1950s.
<?php
function html ($code , $id="", $class=""){
if ($id !== "") $id = " id = \"$id\"" ;
$class = ($class !== "")? " class =\"$class\"":">";
$open = "<$code$id$class";
$close = "</$code>";
return function ($inner = "") use ($open, $close){
return "$open$inner$close";};
}
$layout =
array('container','header','pmain','lsidebar','rsidebar','footer');
foreach ($layout as $element)
$$element = html ("div", $element);
$div = html("div", "test");
$bold = html('strong');
$italic = html('i');
$msg= $div($bold($italic("hello from the left sidebar")));
echo $container(
$header(
"This is the header").$pmain(
$lsidebar(
$msg).$rsidebar(
"This is the right sidebar")).$footer(
));
----
Server IP: 69.147.83.197
Probable Submitter: 24.149.51.104
----
Manual Page -- http://www.php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/106046
Del: integrated -- https://master.php.net/note/delete/106046/integrated
Del: useless -- https://master.php.net/note/delete/106046/useless
Del: bad code -- https://master.php.net/note/delete/106046/bad+code
Del: spam -- https://master.php.net/note/delete/106046/spam
Del: non-english -- https://master.php.net/note/delete/106046/non-english
Del: in docs -- https://master.php.net/note/delete/106046/in+docs
Del: other reasons-- https://master.php.net/note/delete/106046
Reject -- https://master.php.net/note/reject/106046
Search -- https://master.php.net/manage/user-notes.php