قوانین PHP

اسکریپت PHP روی سرور اجرا می‌شود و سپس نتایج خالص HTML به مرورگر ارسال می‌شود.

زبان برنامه‌نویسی پایه PHP

اسکریپت PHP می‌تواند در هر جای سند قرار گیرد.

اسکریپت PHP با <?php شروع، با ?> پایان:

<?php
// اینجا کد PHP است
?>

نام پیش‌фикس فایل‌های PHP به طور پیش‌فرض ".php" است.

فایل‌های PHP معمولاً شامل تگ‌های HTML و برخی کدهای اسکریپت PHP هستند.

در زیر مثالی از یک فایل PHP ساده آورده شده است که شامل یک کد PHP است که از تابع داخلی "echo" برای نمایش متن "Hello World!" در وب‌سایت استفاده می‌کند:

Example

<!DOCTYPE html>
<html>
<body>
<h1>صفحه اول PHP من</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

Run Instance

توضیحات:جملات PHP با کاما (؛) پایان می‌یابند. تگ‌های بسته‌بندی کد PHP نیز به طور خودکار نشان‌دهنده کاما هستند (بنابراین در آخرین خط کد بسته‌بندی PHP نیازی به استفاده از کاما نیست).

توضیحات در PHP

توضیحات کد PHP به عنوان یک برنامه خوانده و اجرا نمی‌شود. تنها کاربرد آن این است که برای ویرایشگر کد قابل خواندن باشد.

توضیحات برای:

  • کارهایی که انجام می‌دهید را برای دیگران قابل فهم کنید - توضیحات می‌تواند به برنامه‌نویسان دیگر کمک کند تا بدانند در هر مرحله چه کاری انجام می‌دهید (اگر در تیمی کار می‌کنید)
  • Remind yourself of what you have done - most programmers have experienced having to go back to a project after one or two years and reconsider what they have done. Comments can record your thoughts when writing code.

PHP supports three types of comments:

Example

<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is a single-line comment
/*
This is a multiline comment block
It spans
Multiline
*/
?>
</body>
</html>

Run Instance

PHP Case Sensitivity

In PHP, all user-defined functions, classes, and keywords (such as if, else, echo, etc.) are not case-sensitive.

In the following example, all three echo statements are valid (equivalent):

Example

<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>

Run Instance

However, in PHP, all variables are case-sensitive.

In the following example, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are considered three different variables):

Example

<!DOCTYPE html>
<html>
<body>
<?php
$color="red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>

Run Instance