0% found this document useful (0 votes)
27 views27 pages

PHP Chapter 2

Uploaded by

taj200153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views27 pages

PHP Chapter 2

Uploaded by

taj200153
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Web Applications

Development
ITSE 3302
‫تطوير تطبيقات الشبكة العالمية‬
Dr. Moamar Elyazgi
PHP Language
Chapter 2
PHP
Variable Types & Constants
Dr. Moamar Elyazgi
2.1 Variable Types
 The main way to store information in the middle of a PHP program is
by using a variable. Here are the most important things to know about
variables in PHP.
• All variables in PHP are denoted with a leading dollar sign ($).
• The value of a variable is the value of its most recent assignment.
• Variables are assigned with the = operator, with the variable on the left-
hand side and the expression to be evaluated on the right.
• Variables can, but do not need, to be declared before assignment. 3
2.1 Variable Types
• Variables in PHP do not have intrinsic types - a variable does not
know in advance whether it will be used to store a number or a
string of characters.
• Variables used before they are assigned have default values.
• PHP does a good job of automatically converting types from one to
another when necessary.
• PHP variables are Perl-like
4
2.1 Variable Types
PHP has a total of eight data types which we use to construct our
variables:
1. Integers: are whole numbers, without a decimal point, like 4195.
2. Doubles: are floating-point numbers, like 3.14159 or 49.1
3. Booleans: have only two possible values either True or False.
4. NULL: is a special type that only has one value: NULL.
5. Strings: are sequences of characters, like 'PHP supports string
operations.' 5
2.1 Variable Types
6. Arrays: are named and indexed collections of other values.
7. Objects: are instances of programmer-defined classes, which can
package up both other kinds of values and functions that are
specific to the class.
8. Resources: are special variables that hold references to resources
external to PHP (such as database connections).
The first five are simple types, and the next two (arrays and
objects) are compound – the compound types can package up other
arbitrary values of arbitrary type, whereas the simple types cannot.
6
‫‪2.1 Variable Types‬‬
‫‪<?php‬‬
‫عدم اسناد قيمة إبتدائية للمتغير ‪$var1; //‬‬
‫اسناد عدد صحيح‪$var2 = 10 ; //‬‬ ‫‪Example‬‬
‫اسناد عدد كسري ‪$var3 = 10.23; //‬‬
‫اسناد القيمة الفارغة‪$var4 = null ; //‬‬
‫اسناد قيمة منطقية ‪$var5 = false ; //‬‬ ‫هناك قيم أخرى يمكن‬
‫اسناد سلسلة نصية ‪$var6 = “Mahmoud“; //‬‬ ‫إسنادها للمتغير‬
‫اسناد سلسلة نصية ‪$var7 = 'Mostafa’ ; //‬‬ ‫سنتعرف عليها الحقا‬
‫‪ $var1‬الى المتغير ‪$var7‬اسنتد قيمة المتغير ‪$var1 = $var7 ; //‬‬ ‫كالمصفوفات والكائنات‬
‫دمج متغير بمتغير واسناد القيمة المدمجة لمتغير أخر ‪$_ = $var6.$var2 ; //‬‬ ‫و العنوان‬
‫دمج متغير بمتغير واسناد القيمة المدمجة لمتغير أخر ‪$_20 = $var1.$var3 ; //‬‬
‫طباعة المتغيرات مع‪//‬‬
‫;‪echo $var1.$var2.$var3.$var4.$var5.$var6 $var7.$_.$_20‬‬
‫‪7‬‬
‫>?‬
2.1.1 Variable Types - Integer
• Integer variables are able to hold a whole number in the range of
-2147483648 to 2147483647.
• Negative values can be assigned by placing the minus (-) sign after the
assignment operator and before the number.
<?php
$a = 1234; // decimal number (base 10)
$a = 0123; // octal number (equivalent to 83 decimal) (base 8)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal) (base 16)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
8
2.1.2 Variable Types - Doubles
• There are three real floating types, designated as float, double, and long
double. The set of values of the type float is a subset of the set of values
of the type double; the set of values of the type double is a subset of the
set of values of the type long double.
<?php It produces the
$many = 2.2888800; following
browser output:
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);
?> 2.28888 + 2.21112 = 4.5
9
2.1.3 Variable Types - Boolean
• They have only two possible values either true or false. PHP provides a
couple of constants especially for use as Booleans: TRUE and FALSE.
• Booleans are often used in conditional testing. You will learn more about
conditional testing in a later chapter of this tutorial.
• FALSE will yield 0 (zero), and TRUE will yield 1 (one).

if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
10
2.1.4 Variable Types - Null
• NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this: $my_var = NULL;
• A variable of data type NULL is a variable that has no value assigned to it.
• If a variable is created without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
• A variable that has been assigned NULL has the following properties:
• It evaluates to FALSE in a Boolean context.
• It returns FALSE when tested with IsSet() function.
<?php
$x = "Hello world!"; It produces the NULL
$x = null; following browser
var_dump($x); output:
11
?>
2.1.5 Variable Types - Strings
• A string is series of characters, where a character is the same as a byte. This means
that PHP only supports a 256-character set, and hence does not offer native Unicode
support.
• As of PHP 7.0.0, there are no particular restrictions regarding the length of a string
on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as
up to 2GB (2147483647 bytes maximum).
• Following are valid examples of string:
o$string_1 = "This is a string in double quotes";
o$string_2 = "This is a somewhat longer, singly quoted string";
o$string_39 = "This string has thirty-nine characters";
12
o$string_0 = ""; // a string with zero characters
2.1.5 Variable Types - Strings
• Singly quoted strings are treated almost literally, whereas doubly quoted strings
replace variables with their values as well as specially interpreting certain character
sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?> It produces the
My $variable will not print!\n
following
browser output: My name will print
13
2.1.5 Variable Types - Strings
• There are no artificial limits on string length -
within the bounds of available memory, you
ought to be able to make arbitrarily long • The escape-sequence replacements
strings. are:
\n is replaced by the newline character
• Strings that are delimited by double quotes \r is replaced by the carriage-return
(as in "this") are preprocessed in both the character
following two ways by PHP: \t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
o Certain character sequences beginning with
\" is replaced by a single double-quote (")
backslash (\) are replaced with special
\\ is replaced by a single backslash (\)
characters. (Explained in Chapter 1 -
Section Escaping to PHP).
o Variable names (starting with $) are replaced
14
with string representations of their values.
2.2 Variable Naming
• Rules for naming a variable is:
o Variable names must begin with a letter or underscore character.
o A variable name can consist of numbers, letters, underscores but you
cannot use characters like + , - , % , ( , ) . & , etc
o There is no size limit for variables.
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"
$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.
?>
15
2.3 PHP is case sensitive
This will produce the following result:
<html>
<body>
<?
$capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html> Variable capital is 67
Variable CaPiTaL is
16
2.4 Variable Scopes
• Scope can be defined as the range of availability a variable has to the
program in which it is declared. PHP variables can be one of four scope
types:
1. Local variables
2. Global variables
3. Function parameters
4. Static variables
17
2.4.1 PHP Local Variables
• A variable declared within a PHP function is local and can only be accessed
within that function. (the variable has local scope):

<?php • The script will not produce any output because the
$a = 5; // global echo statement refers to the local scope variable $a,
scope which has not been assigned a value within this
function myTest() scope.
• You can have local variables with the same name in
{
different functions, because local variables are only
echo $a; // local recognized by the function in which they are
scope declared.
} • Local variables are deleted as soon as the function is
myTest(); completed.
?>
18
2.4.2 PHP Global Variables
<?php
• Global scope refers to any
$a = 5;
variable that is defined $b = 10;
outside of any function. function myTest()
• Global variables can be {
The script
accessed from any part of global $a, $b;
above
the script that is not inside a $b = $a + $b;
will 15
function. }
myTest(); output
• To access a global variable
echo $b;
from within a function, use
?>
the global keyword::
19
2.4.2 PHP Global Variables
• PHP also stores all global The previous example can be rewritten
variables in an array as this:
called <?php
$GLOBALS[index]. $a = 5; The script will
• Its index is the name of $b = 10; output
the variable. function myTest()
{
• This array is also
$GLOBALS['b'] = $GLOBALS['a']
accessible from within + $GLOBALS['b']; 15
functions and can be used }
to update global variables myTest();
directly. echo $b;
?> 20
2.4.3 PHP Function Parameters
• In short, a function is a
small unit of program
which can take some input <?
// multiply a value by 10 and
in the form of parameters The script will
return it to the caller
and does some processing output
function multiply ($value) {
and may return a value. $value = $value * 10;
• Function parameters are return $value;
declared after the function } Return
name and inside $retval = multiply (10); value is
parentheses. They are Print "Return value is $retval\n"; 100
?>
declared much like a
typical variable would be: 21
2.4.4 PHP Static Variables
• In contrast to the You can declare a variable to be static simply by
placing the keyword STATIC in front of the variable
variables declared as name.
function parameters, <?
function keep_track() { The script will
which are destroyed on output
the function's exit, a STATIC $count = 0;
$count++;
static variable will not print $count;
lose its value when the print ""; 1
function exits and will } 2
keep_track(); 3
still hold that value keep_track();
should the function be keep_track();
called again. ?> 22
2.5 PHP ─ Constants
• A constant is a name or an identifier for a simple value.
• A constant value cannot change during the execution of the script.
• By default, a constant is case-sensitive.
• By convention, constant identifiers are always uppercase.
• A constant name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores.
• If you have defined a constant, it can never be changed or
undefined.

23
2.5 PHP ─ Constants
• To define a constant you have to use define() function
and to retrieve the value of a constant, you have to
simply specifying its name. <?php
• Unlike with variables, you do not need to have a define("MINSIZE", 50);
constant with a $. echo MINSIZE;
• You can also use the function constant() to read a echo constant("MINSIZE"); //
constant's value if you wish to obtain the constant's same thing as the previous line
name dynamically. ?>
constant() function The script
• As indicated by the name, this function will return the will output
value of the constant.
• This is useful when you want to retrieve value of a
constant, but you do not know its name, i.e., it is stored
in a variable or returned by a function.
• Only scalar data (boolean, integer, float and string) can
5050 24

be contained in constants.
2.6 Differences between Constants and Variables

• There is no need to write a dollar sign ($) before a constant, where


as in Variable one has to write a dollar sign.
• Constants cannot be defined by simple assignment, they may only
be defined using the define() function.
• Constants may be defined and accessed anywhere without regard
to variable scoping rules.
• Once the Constants have been set, may not be redefined or
undefined.

25
2.7 Valid and Invalid Constant Names
• // Valid constant names <?php
• define("ONE", "first thing"); define("GREETING", "Welcome to you");
• define("TWO2", "second thing");
function myTest()
• define("THREE_3", "third thing")
{
• // Invalid constant names echo GREETING;
• define("2TWO", "second thing"); }
• define("__THREE__", "third value");
myTest();
?>

The out put Welcome to you 26


27

You might also like