PHP Variables

7 min read

Variables are “containers” for storing information.

Хувьсах хэмжигдэхүүнүүд нь мэдээллийг хадгалах “сав” юм.

Creating (Declaring) PHP Variables #

PHP-ийн хувьсагчуудыг бий болгох (Declaring) #

In PHP, a variable starts with the $ sign, followed by the name of the variable: – PHP дээр хувьсагч $ тэмдэгээр эхэлж дараа нь хувьсагчийн нэр орно:

Example #

 
<?php $txt = "Hello world!"; $x = 5; $y = 10.5; ?>

After the execution of the statements above, the variable $txt will hold the value Hello world!, the variable $x will hold the value 5, and the variable $y will hold the value 10.5. – Дээрх кодыг хийсний дараа $txt хувьсагч Hello world!, $x хувьсагч 5, $y хувьсагч 10.5 гэсэн утгатай байна.

Note: When you assign a text value to a variable, put quotes around the value.

Тэмдэглэл: Та хувьсагч текстийн утга өгөхдөө утгын эргэн тойронд хашилт оруулна уу.

Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.

Тэмдэглэл: PHP нь бусад програмчлалын хэлүүдээс ялгаатай нь хувьсагч зарлах командгүй байдаг. Энэ нь анхны утга өгөх үеийг бий болгодог.

PHP Variables – PHP Хувьсагчид #

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). – Хувьсагч нь богино нэртэй (x ба y) эсвэл илүү тодорхойлсон нэртэй (нас, машины нэр үндсэн_ая)

Rules for PHP variables:

PHP хувьсагчийн дүрмүүд

  • A variable starts with the $ sign, followed by the name of the variable – Хувьсагч $ тэмдгээс эхэлж дараа нь хувьсагчийн нэр орно

  • A variable name must start with a letter or the underscore character – Хувьсах нэр нь үсэг эсвэл доогуур зураасаар эхлэх ёстой.

  • A variable name cannot start with a number – Хувьсах нэр нь тоогоор эхлэх боломжгүй

  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) – Хувьсах нэр нь зөвхөн альфа – тоон тэмдэгтүүд болон доогуур зураас (A-z, 0-9, and _ ) агуулж болно.

  • Variable names are case-sensitive ($age and $AGE are two different variables) – Хувьсах нэрс нь том жижиг үсгээр бичихээс хамаарна.($age and $AGE are two different variables)

Output Variables Гадуур хувьсагчид #

The PHP echo statement is often used to output data to the screen. – PHP echo -г ихэвчлэн дэлгэцэн дээр өгөгдөл гаргахад ашигладаг.

The following example will show how to output text and a variable: – Текст болон хувьсагчийг хэрхэн яаж гаргахыг дараах жишээн дээр харуулъя.

Example #

Жишээ #

 
<?php $txt = "Apprentice.mn"; echo "I love $txt!"; ?>

The following example will produce the same output as the example above: – Дараах жишээн дээр дээрхи жишээтэй ижил үр дүн гарах болно:

Example #

Жишээ #

<?php $txt = "Apprentice.mn"; echo "I love " . $txt . "!"; ?>

The following example will output the sum of two variables: – Дараах жишээ нь 2 хувьсагчийн нийлбэрийг гаргах болно:

Example #

Жишээ #

<?php $x = 5; $y = 4; echo $x + $y; ?>

Note: You will learn more about the echo statement and how to output data to the screen in the next chapter.

Тэмдэглэл: Та echo мэдэгдэл болон дэлгэцэн дээр хэрхэн яаж өгөгдөл гаргах талаар дараагийн хэсгээс олж мэдэх болно.

PHP is a Loosely Typed Language – PHP  бол чөлөөтэй бичигдсэн хэл юм #

In the example above, notice that we did not have to tell PHP which data type the variable is. – Дээрхи жишээнд PHP- д хувьсагч ямар өгөгдлийн төрөл болохыг хэлэх боломжгүйг анхаарна уу.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error. – PHP нь өгөгдлийн төрлөөс хамааран өгөгдлийн төрлийг автоматаар холбодог. Өгөгдлийн төрлийг хатуу утгаар тохируулаагүй тул бүхэл тоонд мөр нэмэх алдаа гаргалгүйгээр хийх боломжтой. 

In PHP 7, type declarations were added. This gives an option to specify the data type expected when declaring a function, and by enabling the strict requirement, it will throw a “Fatal Error” on a type mismatch. – PHP7-д мэдүүлгийн төрлийг нэмж оруулсан. Энэ нь функцыг зарлахад хүлээгдэж буй өгөгдлийн төрлийг тодорхойлох сонголтыг өгч, хатуу шаардлагыг идэвхжүүлснээр “Fatal Error”-г тохирохгүй байдалд оруулах болно.

You will learn more about strict and non-strict requirements, and data type declarations in the PHP Functions chapter. – Хатуу ба хатуу бус шаардлага, өгөгдлийн төрлийг мэдүүлэх талаар та PHP функц бүлгээс илүү ихийг мэдэх болно.

PHP Variables Scope – PHP хувьсагчийн хамрах хүрээ #

In PHP, variables can be declared anywhere in the script. – PHP хувьсагчдыг скриптын хаана ч зарлаж болно.

The scope of a variable is the part of the script where the variable can be referenced/used. – Хувьсагчийн хамрах хүрээ гэдэг нь тухайн хувьсагчийг иш татах/ашиглах боломжтой скриптийн хэсэг юм.

PHP has three different variable scopes: – PHP нь 3 хувьсах хамрах хүрээтэй:

  • local- дотоод

  • global-Олон улсын 

  • static – Статик

Global and Local Scope – Дэлхийн болон дотоодын хамрах хүрээ #

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function: – Функцын гадна зарлагдсан хувьсагч нь GLOBAL SCOPE-тэй бөгөөд зөвхөн функцын гадна хандах боломжтой.

Example #

Жишээ #

Variable with global scope:

Олон улсын хамрах хүрээтэй хувьсагч: 

<?php $x = 5; // global scope function myTest() { // using x inside this function will generate an error - энэ функцд х-ийг ашиглавал алдаа гарах болно echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function: – Функц дотор зарлагдсан хувьсагч дотооддоо хамрах хүрээтэй бөгөөд зөвхөн тухайн функцед нэвтрэх боломжтой. 

Example #

Жишээ #

Variable with local scope:

Дотоодын хамрах хүрээтэй хувьсагч:

<?php function myTest() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } myTest(); // using x outside the function will generate an error - функцээс гадна х-ийг ашигласнаар алдаа гарах болно echo "<p>Variable x outside function is: $x</p>"; ?>

PHP The global Keyword  #

PHP олон улсын түлхүүр үг #

The global keyword is used to access a global variable from within a function. – Глобал түлхүүр үгийг функц дотроос глобал хувьсагч руу нэвтрэхэд ашигладаг.

To do this, use the global keyword before the variables (inside the function): – Үүнийг хийхийн тулд хувьсагчдын өмнө (функц дотор) глобал түлхүүр үгийг ашиглана уу 

Example #

Жишээ #

<?php $x = 5; $y = 10; function myTest() { global $x, $y; $y = $x + $y; } myTest(); echo $y; // outputs 15 ?>

PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly. – PHP нь дэлхийн бүх хувьсагчдыг $GLOBALS[index] нэртэй массивт хадгалдаг. index нь хувьсагчийн нэрийг агуулдаг. Энэ массивэн дотрох функцээс хандах боломжтой бөгөөд дэлхийн хувьсагчдыг шууд шинэчлэхэд ашиглаж болно.

The example above can be rewritten like this: – Дээрх жишээг дараах байдлаар бичиж болно:

Example #

Жишээ #

<?php $x = 5; $y = 10; function myTest() { $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; } myTest(); echo $y; // outputs 15 ?>

PHP The static Keyword – PHP статик түлхүүр үг #

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. – Ихэнхдээ функц дуусахад/гүйцэтгэхэд түүний бүх хувьсагчид устдаг. Гэсэн хэдии ч бид дотоодын хувьсагч устгагдахгүй байхыг хүсдэг. Энэ нь бидний цаашдын ажилд хэрэгтэй.

To do this, use the static keyword when you first declare the variable: – Үүнийг хийхийн тулд анх зарлахдаа статик түлхүүр үгийг ашиглана уу:

Example #

Жишээ #

<?php function myTest() { static $x = 0; echo $x; $x++; } myTest(); myTest(); myTest(); ?>

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called. – Дараа нь хувьсагч дуудагдах бүрт тухайн хувьсагч функцыг хамгийн сүүлд дуудахаас өгөгдсөн мэдээлэлтэй байх болно.

Note: The variable is still local to the function.

Тэмдэглэл: Хувьсагч нь тухайн функцэд тохирсон хэвээр байна.

Powered by BetterDocs

Leave a Reply