PHP Variable

จาก Wiki2

ข้ามไปที่: นำทาง, สืบค้น

เนื้อหา

Variable requirement

Variable ของ PHP ทำให้ PHP เป็นภาษาที่ง่าย

  • Variable ของ PHP จะต้องนำหน้าด้วยเครื่องหมาย "$" เช่น $firstname
  • Variable เป็น Case Sensitive
  • Variable ต้องใช้ตัวอักษรต่อจาก $ เท่านั้น
  • Variable ประกอบด้วยตัวอักษร และตัวเลข และเครื่องหมาย "_" เท่านั้น
  • Variable ไม่ต้องมี Type จะใช้ใส่อะไรก็ได้
  • Variable ไม่ต้อง Define ก่อนใช้ แต่ Define โดยการ Assign
  • การ Assign ค่าของ Variable ดังตัวอย่าง

$username = "joe";

Scalar

คือ Variable ที่มีค่าเพียงค่าเดียว

Array

คือ Variable ที่เก็บค่าได้หลายๆค่า หรือแม้แต่เป็น Array อื่นก็ได้ ซึ่งใช้มากเวลาติดต่อกับ Database

Local and Global Variables

ควรพยายามใช้ Global Variable ให้น้อยไว้นะครับ

Pre-Defined Variable

มีประโยชน์มากสามารถนำมาใช้ในโปรแกรมที่ต้องการ System Parameter

Pre-Defined Variable ใน PHP ดูได้จาก function phpinfo()

นอกจากนั้นยังมี Superglobals variable ซึ่งโดยมากเป็น Array variable

  • $_GET contains any variables provided to a script through the GET method.
  • $_POST contains any variables provided to a script through the POST method.
  • $_COOKIE contains any variables provided to a script through a cookie.
  • $_FILES contains any variables provided to a script through file uploads.
  • $_ENV contains any variables provided to a script as part of the server environment.
  • $_SESSION contains any variables that are registered in a session.

Constant

มีทั้ง Predefine และ User-defined type ซึ่งไม่สามารถ Redefine

  • ใช้ตัวใหญ่
  • ไม่ต้องมี $
  • ต้อง Define ด้วยคำสั่ง

define("MYCONSTANT", "This the value assign to constant");

ตัวอย่าง Predefine Constant

  • __FILE__ The name of the script file being parsed.
  • __LINE__ The number of the line in the script being parsed.
  • PHP_VERSION The version of PHP in use.
  • PHP_OS The operating system using PHP.
รับข้อมูลจาก "http://www.noklek.com/wiki2/index.php/PHP_Variable"
เครื่องมือส่วนตัว