Senin, 03 Agustus 2015

Mengenal Function PHP

Function atau fungsi merupakan sejumlah pernyataan yang dikemas dalam sebuah nama. Nama ini selanjutnya dapat dipanggil berkali-kali di beberapa tempat pada program.

Tujuan penggunaan fungsi adalah:
  • Memudahkan dalam mengembangkan program
  • Menghemat ukuran program
Untuk membuat fungsi, harus mengikuti sintaks sebagai berikut:


function namafungsi ($parameter1, $parameter2)
{
pernyataan1;
pernyataan2;
}


Contoh 1 : membuat fungsi yang tidak mempunyai parameter


Nama file : fungsi1.php

<?
function BukaTabel()
{
echo "<table align=center width=\"80%\" border=0 cellspacing=1
cellpadding=0 bgcolor=#555555><tr><td>\n";
echo "<table width=\"100%\" border=0 cellspacing=1 cellpadding=8
bgcolor=#ffffff><tr><td>\n";
echo "<center>";
}function TutupTabel()
{
echo "</td></tr></table></td></tr></table>\n";
}
?>

<html>
<head>
<title> Latihan Fungsi 1 </title>
</head>
<body>
<?php
BukaTabel();
print ("Ini tabel pertama");
TutupTabel();
print ("<br>");

BukaTabel();
print ("Ini tabel kedua");
TutupTabel();
?>
</body>
</html> 



Contoh 2 : membuat fungsi yang mempunyai parameter

Nama file : fungsi2.php

<?
function BukaTabel($warna1, $warna2)
{
echo "<table align=center width=\"80%\" border=0 cellspacing=1
cellpadding=0 bgcolor=\"$warna1\"><tr><td>\n";
echo "<table width=\"100%\" border=0 cellspacing=1 cellpadding=8
bgcolor=\"$warna2\"><tr><td>\n";
echo "<center>";
}function TutupTabel()
{
echo "</td></tr></table></td></tr></table>\n";
}
?>

<html>
<head>
<title> Latihan Fungsi 2 </title>
</head>
<body>
<?php
BukaTabel("red", "#dddddd");
print ("Ini tabel pertama");
print ("<table border=1 width=100%>");
print ("<tr><td width=33% align=center> Kolom 1 </td>");
print ("<td width=33% align=center> Kolom 2 </td>");
print ("<td width=* align=center> Kolom 3 </td> </tr>");
print ("</table>");
TutupTabel();
print ("<br>");
BukaTabel ("blue", "white");
print ("Ini tabel kedua");
TutupTabel();
?>
</body>
</html>

0 komentar:

Posting Komentar