Tutorial PHP Function akan menjelaskan cara membuat function anda sendiri (user defined function). Function memudahkan anda untuk tidak menulis kode yang sama berulang kali. Apa yang akan Anda pelajari:
Cara membuat function atau deklarasi function; Menggunakan function disemua halaman web; Argumen function, Membuat function dengan argumen tak terhingga; Anonymous function.
Membuat Function
Untuk membuat function digunakan kata tercadang function, seperti:
1. 2. 3. 4. function namaFunction(){ //badan function //berisi kode php untuk dieksekusi }
contoh:
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. <?php function showName(){ echo "My name is MyPHPtutorials"; } function getUrl(){ return "http://www.myphptutorials.com"; } ?> <html> <head> <title>Contoh PHP Function</title> </head> <body> <div> <?php showName();?> </div> <div> Website: <?php echo getUrl();?> </div> </body> </html>
kemudian buat file lain yang menggunakan function di atas, dan include file function.php menggunakan statement include_once
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. <?php //file index.php include_once "function.php"; //include file function.php ?> <html> <head> <title>Contoh PHP Function</title> </head> <body> <div> <?php showName();?> </div> <div> Website: <?php echo getUrl();?> </div> </body> </html> <?php //file about.php include_once "function.php"; ?> <html> <head> <title>About <?php showName();?></title> </head> <body> Website: <?php echo getUrl();?> </body> </html>
Argumen Function
Informasi bisa diberikan kepada function melalui argumen argumen atau paremeter paremeter yang dipisahkan tanda koma ",". Format:
1. function namaFunction($argumen1, $argument2){ 2. 3. }
contoh:
1. function tambah($a, $b){ 2. $hasil = $a+$b; 3. echo $hasil; 4. }
Anonymous Function
Anonymous function atau closures adalah function tanpa nama function. Kegunaan utamanya sebagai Callback parameter. Contoh:
1. 2. 3. 4. echo reg_replace_callback('/google/i', function($match){ return '<a href="http://google.com">'.$match[0].'</a>'; }, 'go to google'); //hasil go to <a href="http://google.com">google</a>