إعلانيمكن أن تكون علامتك التجارية هناعلامتك التجارية هنافي كل صفحة من Darslab · طلاب وأولياء أمور ومعلمونinfo@darslab.comاسأل عن الأسعارالأسعارinfo@darslab.com
☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

PHP basics: echo, variables and constants

الأسبوع 10 · الوحدة ٣ «إنشاء صفحات الموقع» (٣) الموضوع الأول (تابع): كود PHP في الصفحة، echo وprint، التعليقات، المتغيرات وعلامات الاقتباس والأنواع، الثوابت · 3 دروس
3

Constants

ICT Secondary 2 Term 1, Unit 3, Topic 1: pp. 78–82
GoalDefine and use a constant, and say how it differs from a variable.
New words
constant · a named value that cannot change after it is defineddefine · the PHP function that creates a constant: define('NAME', value)case-sensitive · PHP treats CLUB and club as two different namesplaceholder · an invented value used in lessons instead of a real secret
Explanation

A constant is a name with a value that cannot change. You create it with define, giving the name and the value: define('CLUB', 'Nile Club'). By habit constant names are written in capitals. You use a constant without a dollar sign: echo 'Club: ' . CLUB; Constants suit values that must stay the same through the whole site, such as the club’s name or the largest number of books a member may borrow. If you try to define the same constant again, PHP gives a warning and keeps the first value. Be careful with letter case. The book says that a third argument can make a constant case-insensitive, but in PHP 8 that argument is ignored and gives a warning, so treat constant names as case-sensitive, just like variable names. Never type a real password into a constant in lessons: later we will use invented placeholders only.

Php
1<?php
2define('CLUB', 'Nile Club');
3echo 'Club: ' . CLUB;
4?>
Output
Club: Nile Club
Worked examples
Php
1<?php
2define('MAX_BOOKS', 5);
3$have = 3;
4echo "You may borrow " . (MAX_BOOKS - $have) . " more";
5?>
Output
You may borrow 2 more
A constant for the borrowing limit is used in a calculation. A member has 3 books, the limit is 5, so the page can say how many more he or she may borrow: 5 − 3 = 2. The limit is written once and used everywhere.
VariableConstant
Starts with$no sign
Value can change?yesno
How it is created$level = 7;define('LEVEL', 7);
Case-sensitive?yesyes
Mona compares a variable with a constant. A variable holds a value that may change and has a dollar sign. A constant is set once, cannot change and has no dollar sign.
Class activity

Think of three values on a school site that should be constants (for example the school’s name, the pass mark and the number of days in the week). Write the three define lines on paper and one echo line that prints a sentence with one of them.

Practice
1
What does define('LIMIT', 3); do?
2
What does echo LIMIT + 2; print after that?
3
Do you write a dollar sign before a constant’s name?
4
Is a constant name case-sensitive in PHP 8, and what happens to the third argument of define?