October 14th, 2009
API functions
If you were going to separate code PHP from HTML a code, you have two variants. One way – creation of functions of dynamic formation of a conclusion and to place them in the necessary place on web – page.
If you were going to separate code PHP from HTML a code, you have two variants. One way – creation of functions of dynamic formation of a conclusion and to place them in the necessary place on web – page.
For example, so:
index.php – a code of page
<? php include_once (“site.lib”);?>
<html>
<head>
<title> <? php print_header ();?> </title>
</head>
<body>
<h1> <? php print_header ();?> </h1>
<table border = “0″ cellpadding = “0″ cellspacing = “0″>
<tr>
<td width = ” 25 % “>
<? php print_links ();?>
</td>
<td>
<? php print_body ();?>
</td>
</tr>
</table>
</body>
</html>
site.lib – the code of the program
<? php
$dbh = mysql_connect (“localhost”, “sh”, “pass”)
or die (sprintf (” I can not open connection with MySQL [%s]: %s “,
mysql_errno (), mysql_error ()));
@mysql_select_db (“MainSite”)
or die (sprintf (” I can not choose a database [%s]: %s “,
mysql_errno (), mysql_error ()));
$sth = @mysql_query (” SELECT * FROM site “, $dbh)
or die (sprintf (” I can not execute search [%s]: %s “,
mysql_errno (), mysql_error ()));
$site_info = mysql_fetch_object ($sth);
function print_header ()
{
global $site_info;
print $site_info-> header;
}
function print_body ()
{
global $site_info;
print nl2br ($site_info-> body);
}
function print_links ()
{
global $site_info;
$links = explode (“n”, $site_info-> links);
$names = explode (“n”, $site_info-> link_names);
for ($i = 0; $i <count ($links); $i ++)
{
print ” ttt
<a href = ” $ links [$i] “> $names [$i] </a>
n <br> n “;
}
}
?>
Obviously, such code is better readable. One more advantage of use of this concept – an opportunity of change of design without updating the code of the program.
Pluss of use API of functions
* Rather pure{clean}, clear code
* A fast code