Tutorial PHP Dasar Part 7: Aturan Penulisan Kode PHP

Brian Harris / / PHP, PHP Dasar
aturan penulisan pada script php

Setelah sebelumnya kita sudah membahas tentang cara input kode PHP ke HTML, sekarang kita akan membahas mengenai aturan penulisan kode PHP. Sebelum kita bermain-main dengan script PHP yang lebih banyak lagi, ada baiknya jika kita mulai dengan hal-hal mendasar yang  harus diperhatikan dalam PHP, di antaranya adalah aturan penulisan PHP. Disini kita akan mempelajari beberapa aturan penulisan dasar pada kode PHP dan akan kita praktekkan secara langsung beberapa aturan tersebut. Ada beberapa aturan penulisan script PHP yang harus kita perhatikan. Penasaran? Langsung saja kita simak bersama-sama.


Aturan Penulisan PHP

1. Permulaan Pada Kode PHP

Permulaan kode PHP harus diawali dengan <?php atau bisa disingkat dengan <?. Tapi, menyingkat penulisan kode PHP seperti tadi, jarang saya temukan orang yang menggunakan itu.

2. Akhir Pada Kode PHP

Akhir kode PHP bisa ditutup dengan menambahkan tag ?> pada akhir kode PHP.

3. Akhir Baris Program PHP

Setiap baris intruksi program pada PHP diakhiri dengan titik koma (;). Hal ini berarti walaupun kita tulis lebih dari 1 baris, hal tersebut akan tetap dianggap hanya satu baris apabila belum diberikan titik koma.

4. Tanda Kurung

Tanda kurung akan lebih banyak digunakan dalam kode PHP. Karena salah satu kegunaan (fungsi) tanda kurung untuk memanggil sebuah fungsi. Nah setiap fungsi pada PHP akan seperti ini:

print ();

Perlu diketahui bahwa print merupakan nama fungsi dan informasi lain yang perlu ditambahkan pada fungsi tersebut dan akan kita letakkan didalam tanda kurung dan kita akhiri dengan tanda titik koma (;). Selan itu, ada juga fungsi lain yang sama dengan print, yaitu echo ();.

5. Case Sensitive Pada PHP

Salah satu aturan penulisan PHP adalah tidak adanya perbedaan format huruf besar dan kecil (case sensitive) untuk penulisan fungsi, class yang dideklarasikan sendiri, maupun constructor bawaan PHP seperti print, echo, for, while dan class. Supaya lebih mengerti silahkan lihat contoh dibawah ini, keempat baris dibawah akan dianggap sama.

<?php 
	echo "Belajar PHP itu Mudah!";
	ECHO "Belahar PHP itu mudah!";
	Echo "Belajar PHP itu Mudah!";
	EcHo "Belajar PHP itu mudah!";
 ?>

Untuk mempermudah mengetahui perbedaan case insensitive ini, saya sengaja menggunakan huruf besar dan huruf kecil pada kode PHP-nya, kalian bisa melihat pada bagian “echo”. Tapi sayangnya, PHP tidak membedakan antara huruf besar dan kecil (case sensitive) untuk penulisan variabel, sehingga misalnya kita membuat 3 (tiga) variabel dengan nama $brian, $Brian, dan $BRIAN itu akan dianggap berbeda. Kesalahan ini paling sering terjadi pada penulisan variabel, sehingga kita harus lebih teliti saat menggunakan/menulis sebuah variabel. Untuk mengatasi hal tersebut, kita gunakan huruf kecil untuk semua variabel di seluruh kode PHP. Tidak hanya variabel yang dianjurkan/disepakati oleh programmer untuk ditulis dengan huruf kecil, tapi fungsi ataupun class juga dianjurkan ditulis dengan huruf kecil. Apabila anda ingin membuat variabel dengan 2 kata, kita bisa menggunakan underscore (_) untuk mengganti karakter spasi.

6. Penulisan Baris Perintah PHP

Statement atau bisa disebut dengan baris perintah merupakan kumpulan perintah PHP yang menginstrusikan PHP untuk melakukan sesuatu, misalnya dalam keadaan kondisi tertentu. Baris perintah seperti ini terdiri atas satu baris singkat, contohnya perintah echo (untuk mencetak/menampilkan text), if (untuk pengkondisian) atau looping (pengulangan).

<?php 
	echo "Belajar PHP itu mudah!";
	sebuah_fungsi(21, "Belajar PHP");
	$a = 1;
	$nama = "Iltekkomputer.com";
	$b = $a / 25.0;
	if ($y == $z){
		echo "Tampilkan tabel";
	}
 ?>

Selanjutnya, kita bisa melihat dari contoh kode diatas, penulisan script PHP menggunakan titik koma (semicolon) sebagai tanda akhir baris perintah PHP. Tapi, khusus untuk penulisan fungsi IF atau looping (perulangan) tidak membutuhkan titik koma setelah kurung tutup.

<?php 
	//cek apakah kondisi true
	if (true) {
		//jangan lupakan titik koma
		echo "Baris ini akan dijalankan";
		
	} //setelah kurung kurawal tutup, tidak perlu titik koma
 ?>

7. Karakter Spasi dan Tab PHP

Karakter spasi dan tab sering sekali diabaikan pada eksekusi program PHP. Artinya kita bisa memecah sebuah statement (baris perintah) menjadi beberapa baris atau menyatukan beberapa statement dalam sebuah baris yang panjang.

<?php 
	echo "ini adalah kalimat pertama"; echo "ini adalah kalimat kedua"; $nama = "iltekkomputer.com";
?>

Dan lihat kode PHP dibawah ini, meskipun hasilnya sama saja.

<?php 
	echo "ini adalah kalimat pertama";
	echo "ini adalah kalimat kedua";
	$nama = "iltekkomputer.com";
?>

Terlihat bedanya bukan? Kalian bisa menggunakan cara yang pertama atau yang kedua, biasanya programmer menggunakan cara yang kedua.

Setelah melihat dua contoh diatas, kita usahakan setiap statament yang berada pada suatu baris dan menambahkan beberapa spasi di awal untuk memudahkan membaca kode program kita sendiri.


Nah kita telah selesai membahas aturan penulisan PHP. Pada kode PHP, kita bisa memberikan sebuah komentar yang berfungsi untuk mencatat/mengingatkan kita pada suatu fungsi yang kita buat, dan komentar tersebut tidak akan dieksekusi oleh web browser. Pada tutorial selanjutnya, kita akan membahas tentang penulisan komentar kode PHP.

15 Komentar

  1. Every weekend i used to pay a visit this web site, for the reason that i wish
    for enjoyment, since this this web site conations truly pleasant funny
    stuff too.

  2. Howdy, I think your blog may be having internet browser compatibility problems.
    Whenever I look at your blog in Safari, it looks fine however, if opening in Internet Explorer,
    it has some overlapping issues. I merely wanted to give you a quick heads up!
    Besides that, excellent site!

  3. With Rocket Rx, you can avoid trips to the drug store and gain access to medication by yourself terms.

    It’s safe, discreet, and quick: your totally free 2-minute assessment is assessed online by a completely licensed US medical group and, if you’re eligible, you’ll get an authentic prescription and a dual-active treatment in just two days.

    No waiting space, no lines, no in-person consultations.

    Strength

    Find the ideal treatment for you

    Not sure? We can help.

    Start a quick assessment to discover what’s right for you.

    Why spend more on a trademark name like Viagra ®? Save 95% with generic medications

    By law, the FDA states generic and top quality drugs should have the same:

    check_circle.
    Active active ingredients.

    check_circle.
    Effectiveness.

    check_circle.
    Quality.

    check_circle.
    Safety.

    check_circle.
    Strength.

    check_circle.
    Benefits.

    How it works

    1Answer a private online assessment in just 2 minutes.

    2Get a complimentary prescription from a US-licensed clinician.

    3Your FDA-approved treatment gets here rapidly and inconspicuously.

    Verified client evaluations

    Rating: 4.4/ 5

    Rating: 4.6/ 5

    ” So fast and easy”

    The whole purchasing process is smooth. The action is really quick and an entirely affordable shipping an …

    The whole purchasing procedure is seamless. The response is really fast and a totally affordable shipping and dealing with charge, under 5 dollars! The prescription …

    ” It’s been working out”

    Smooth, quickly, and discreet shipping!

    ” Similar to the brand”

    Happy to report these are the genuine offer for a great rate and fast delivery. You have my business as long …

    Happy to report these are the genuine offer for a terrific rate and fast delivery. You have my company as long as you stay in business.

    ” Very great”

    Quick action and delivers on time. Will absolutely buy from again.

    ” I feel like I’m 18 again”

    Better than terrific I feel like I’m 18 again! I can go for hours on end and my other half loves it too. I like thi …

    Better than terrific I seem like I’m 18 once again! I can opt for hours on end and my other half likes it too. I like this generic viagra.

    ” Privacy and transparency”

    I simply love the personal privacy and transparency as well as the effective methods of getting the item to me quickl …

    I just love the privacy and openness along with the efficient methods of getting the item to me quickly.

    ” Easiest and most affordable”

    With all the ED websites out there this one by far is the most convenient and one of the most inexpensive

    ” Very pleased with results”

    Happy spouse. Happy marriage. Thanks!

    ” Glad I made the switch”

    Easy to get my prescription with no inconvenience. Fast and quick shipment date. Fast acting in my viewpoint works …

    Easy to get my prescription without any inconvenience. Fast and fast shipment date. Fast acting in my viewpoint works better than viagra. Glad I made the switch. Very a.

    ” I can enjoy life as I should”

    They are considerably assisting me with my ed concerns. I am grateful I can enjoy life as I should.Thank you

    ” Fast and easy”

    My medication arrives discreetely pakaged. I discover it priced well and the total procedure of obtaining the …

    My medication shows up discreetely pakaged. I find it priced well and the total procedure of getting the prescription is fast and easy.

    ” Easy peezy”

    Excellent procedure. Cant be any friendlier. Thank you.

    ” This is remarkable!!!”

    The very best experience I have actually ever had getting the proper treatment, thank you Rocket RX.

    ” Thank goodness for you all!”

    I want to say how much I took pleasure in the private and expedient procedure that RocketRx has readily available to guys that …

    I wish to say how much I took pleasure in the personal and practical process that RocketRx has readily available to guys that require a little aid. I live in a neighborhood where …

    More ED options

    Tadalafil

    Works inAs little as 12 minutes.

    Lastsup to 36 hours.

    Tadalafil Daily

    Generic Cialis ®, from $1.25/ tablet

    Tadalafil Daily, generic for Cialis ®, is taken everyday making it ideal for spontaneous sex without planning.

    Works in3-5 days.

    Lasts forcontinuously.

    Tadalafil

    Generic Cialis ®, from $2.50/ tablet

    Want a lasting ED treatment? Take Tadalafil, the medical equivalent to Cialis ®, an hour before sex.

    Works in30-60 minutes.

    Lasts forup to 36 hours.

    Rocket Launch

    from $4.00/ pill

    Maximize your sexual capacity with Rocket Launch, a high-dose service for impotence.

    * The included products consist of intensified items which have not been authorized by the FDA. The FDA does not verify the safety or efficiency of compounded drugs.

  4. Добро пожаловать в Лев Казино, где каждая игра – это шанс на успех и удачу. Здесь вы найдете широкий ассортимент игр, от классических до новейших. С нами вы можете играть когда угодно, наслаждаясь безопасной и честной игрой с шансами на большой выигрыш.

    Лев Казино отличается высоким качеством сервиса и надежностью. Лев Казино имеет интуитивно понятный интерфейс и множество методов для пополнения и вывода средств, чтобы ваш опыт был комфортным. Для новых игроков в https://levcasino-goldenchips.beauty/ предусмотрены щедрые бонусы и привилегии.

    Мы предлагаем простую регистрацию и быстрое снятие выигрышей, чтобы вы могли наслаждаться игрой без задержек.
    Наши игроки наслаждаются разнообразием игр, начиная от классических слотов и заканчивая инновационными настольными играми.
    В Лев Казино регулярно проходят акции, которые дают дополнительные возможности для выигрыша и увеличения вашего баланса.
    В Лев Казино ваши данные и средства всегда под защитой, и мы гарантируем полную безопасность.

    Начните свою игру в Лев Казино прямо сейчас и станьте победителем, наслаждаясь множеством захватывающих игр.

  5. Woah! I’m really loving the template/theme
    of this blog. It’s simple, yet effective. A lot of times it’s
    difficult to get that “perfect balance” between superb
    usability and visual appeal. I must say that you’ve done
    a very good job with this. Also, tthe blog loads super fast for me on Opera.
    Superb Blog!

  6. I could not refrain from commenting. Well written!

  7. For newest information you have to pay a quick visit world wide web and on internet I found this site as a most excellent web page for most recent
    updates.

  8. Feel confident in your favourite outfits thanks to our luxurybrandusa_allyupoosalesss520 for women.Look and feel good with our collection of women’s luxurybrandusa_allyupoosalesss520. From bodysuits to shaping panties, luxurybrandusa_allyupoosalesss520 will have you feeling amazing about how you look.No matter if you’re looking for a full body shaper or something else, it’s important to get one of the best luxurybrandusa_allyupoosalesss520 garments. There are various reasons why women choose to wear luxurybrandusa_allyupoosalesss520.
    Authentic BAPE shoes https://eutrade.x.yupoo.com

  9. Feel comfortable and confident in our curvy luxurybrandusa_allyupoosalesss520. It can make you look up to 5-inches thinner within seconds. Shed the pounds away with our women’s plus size luxurybrandusa_allyupoosalesss520 todayWomen’s luxurybrandusa_allyupoosalesss520 Bodysuits & Body Shapers | Our bodysuit luxurybrandusa_allyupoosalesss520 smooths your natural shape with firm control and chic designs in strapless and open bust!
    Supreme clothing sizing guide https://xfans.x.yupoo.com

  10. Attractive section of content. I just stumbled upon your site and in accession capital to assert that I get in fact enjoyed account your blog posts.
    Any way I will be subscribing to your augment and even I achievement you access
    consistently rapidly.

    My web page: nordvpn coupons inspiresensation

  11. kinshingsilicone customs_manufacturerHow a Leading Silicone Products Manufacturer Helps Brands Scale Sustainably As sustainability becomes central to consumer and corporate priorities, brands are searching for materials and manufacturers that align with their environmental goals. A leading silicone products manufacturer is not only about precision and performance—it’s also about helping you scale sustainably.
    silicone litter mat https://www.siliconemaking.com

  12. You are so awesome! I don’t think I have read through something like that
    before. So good to find someone with a few genuine thoughts on this subject matter.
    Really.. thank you for starting this up. This web site is one thing that’s needed on the internet, someone with a little originality!

    My site nordvpn coupons inspiresensation

  13. Hello, i think that i saw you visited my blog thus i came to “return the favor”.I am attempting to find things to improve my web site!I suppose its ok
    to use some of your ideas!!

    Feel free to visit my web-site; nordvpn coupons inspiresensation

  14. This information is priceless. Where can I find out more?

    Feel free to surf to my page; Nordvpn coupons inspiresensation (tinyurl.com)

  15. nordvpn discount 350fairfax
    Hello There. I found your weblog the usage of msn. This is a very neatly written article.
    I will make sure to bookmark it and return to learn extra of your helpful info.
    Thanks for the post. I’ll definitely return.

Tinggalkan Komentar

Your email address will not be published. Required fields are marked *