Você está na página 1de 24

PHP Language basics

Variables(Recap)
A variable is simply a container that holds a certain value.
Naming of variables:
Variable names begin with a dollar sign ( $ )
The first character after the dollar sign must be a letter or an underscore
The remaining characters in the name may be letters, numbers, or underscores
without a fixed limit
NOTE: Variable names are case - sensitive ( $Variable and $variable are
two distinct variables)
Examples:
$my_first_variable
$anotherVariable
$x
$_123

2
Variables(Recap)
Creating Variables
Creating a variable in PHP is known as declaring it. Declaring a variable is as
simple as using its name in your script:
$my_first_variable;
NOTE:
Many programming languages prevent you from using a variable without first
explicitly declaring(creating) it.
PHP lets you use variables at any point just by naming them.
However if you happen to use a non-existent variable name by mistake, no error
message is generated, and you may end up with a hard - to - find bug.
Good practice Initialise your variables
$my_first_variable = 3;

3
Variables(Recap)
Understanding data types(Refer to previous lecture)
Loose typing
PHP is known as a loosely - typed language not fussy about the type of data stored in a variable.
It converts a variable s data type automatically, depending on the context in which the variable is used.
EXAMPLE:
Initialize a variable with an integer value; add a float value to it, thereby turning it into a float; then join it onto a string value
to produce a longer string.
In contrast, many other languages, such as Java, are strongly - typed ; once you set the type of a variable in Java, it must
always contain data of that type
Advantages:
Variables are more flexible
No need to worry about specifying the type of a variable when you declare it
HOWEVER, PHP will let you pass a floating - point value to a piece of code that expects to be working on
an integer value
You probably won t see an error message, but you may discover that the output of your script isn t quite
what you expected!

4
Testing the type of a variable
Determine the type of a variable at any time by using PHP s gettype()
function $test_var; // Declares the $test_var variable without initializing it
echo gettype( $test_var ) . < br / > ; // Displays NULL
$test_var = 15;
echo gettype( $test_var ) . < br / > ; // Displays integer
$test_var = 8.23;
echo gettype( $test_var ) . < br / > ; // Displays double
$test_var = Hello, world!;
echo gettype( $test_var ) . < br / > ; // Displays string

NOTE:
To pass a variable to a function, place the variable between parentheses after the
function name for example, gettype( $x ) .
If you need to pass more than one variable, separate them by commas.
5
Type testing functions
You can also test a variable for a specific data type using PHP s
type testing functions:

Function Description
is_int (value) Returns true if value is an integer
is_float (value) Returns true if value is a float
is_string (value) Returns true if value is a string
is_bool (value) Returns true if value is a boolean
is_array (value) Returns true if value is an array
is_object (value) Returns true if value is an object
is_resource (value) Returns true if value is a resource
is_null (value) Returns true if value is null
6
Changing a variables data type
Use PHP s settype() function to change the type of a variable while
preserving the variable s value as much as possible.
$test_var = 8.23;
echo $test_var . < br / > ; // Displays 8.23
settype( $test_var, string );
echo $test_var . < br / > ; // Displays 8.23
settype( $test_var, integer );
echo $test_var . < br / > ; // Displays 8
settype( $test_var, float );
echo $test_var . < br / > ; // Displays 8
settype( $test_var, boolean );
echo $test_var . < br / > ; // Displays 1 7
Change type by casting
Type casting involves placing the name of the desired data type in
parentheses before the variable s name.
Note
The variable itself remains unaffected; this is in contrast to settype() , which
changes the variable s type.
$test_var s type isn t changed at any point; it remains a floating - point
variable, containing the value 8.23 , at all times. All that changes is the type of
the data that s passed to the echo statement.
$test_var = 8.23;
echo $test_var . < br / > ; // Displays 8.23
echo (string) $test_var . < br / > ; // Displays 8.23
echo (int) $test_var . < br / > ; // Displays 8
echo (float) $test_var . < br / > ; // Displays 8.23
echo (boolean) $test_var . < br / > ; // Displays 1 8
Operators & Expressions
An operator is a symbol that manipulates one or more values, usually producing a new value in
the process.
For example, this code uses the addition operator ( + ) to add the values of $x and $y together to
produce a new value:
echo $x + $y;
An expression in PHP is anything that evaluates to a value; this can be any combination of values,
variables, operators, and functions.
In the preceding example, $x + $y is an expression. Here are some more examples of expressions:
$x + $y + $z
$x - $y
$x <5
$error(true)
gettype( $test_var )
The values and variables that are used with an operator are known as operands .

9
Operator types
Operators in PHP can be grouped into ten types, as follows:

10
Arithmetic Operators

Operator Example Is The Same As


= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
The arithmetic operators (plus, minus, and *= x*=y x=x*y
so on) work much as you would expect, /= x/=y x=x/y
enabling you .= x.=y x=x.y
to write expressions as though they were
simple equations. %= x%=y x=x%y
11
Comparison operators
Comparison operators let you compare one operand with the other in
various ways.
If the comparison test is successful, the expression evaluates to true ;
otherwise, it evaluates to false.
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
<> is not equal 5<>8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than 5>=8 returns false
or equal to
<= is less than or 5<=8 returns true
equal to

12
Example of comparison operators
Comparison operators are used with decision and looping statements such as
if and while

$x = 23;
echo ( $x < 24 ) . < br / > ; // Displays 1 (true)
echo ( $x < 24 ) . < br / > ; // Displays 1 (true) because
// PHP converts the string to an integer
echo ( $x == 23 ) . < br / > ; // Displays 1 (true)
echo ( $x === 23 ) . < br / > ; // Displays 1 (true)
echo ( $x === 23 ) . < br / > ; // Displays (false) because
// $x and 23 are not the same data type
echo ( $x > = 23 ) . < br / > ; // Displays 1 (true)
echo ( $x > = 24 ) . < br / > ; // Displays (false)

13
Incrementing /Decrementing Operators
++$x; // Adds one to $x and then returns the result
$x++; // Returns $x and then adds one to it
- $x; // Subtracts one from $x and then returns the result
$x - ; // Returns $x and then subtracts one from it

The location of the operators makes a difference. Placing the operator before the variable name causes the
variable s value to be incremented or decremented before the value is returned; placing the operator after
the variable name returns the current value of the variable first, then adds or subtracts one from the
variable.
For example:
$x = 5;
echo ++$x; // Displays 6 (and $x now contains 6)
$x = 5;
echo $x++; // Displays 5 (and $x now contains 6)

14
EXAMPLE:
<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addition Operation Result: $c <br/>";
$c = $a - $b;
echo "Subtraction Operation Result: $c <br/>";
$c = $a * $b;
echo "Multiplication Operation Result: $c <br/>";
$c = $a / $b;
echo "Division Operation Result: $c <br/>";
$c = $a % $b;
echo "Modulus Operation Result: $c <br/>";
$c = $a++;
echo "Increment Operation Result: $c <br/>";
$c = $a--;
echo "Decrement Operation Result: $c <br/>";
?>

15
Logical operators
Operator Description Example
&& and x=6
y=3
The main use of logical
(x < 10 && y > 1) returns true operators and Boolean
|| or x=6
y=3 logic is when making decisions
(x==5 || y==5) returns false
and creating loops
! not x=6
y=3
!(x==y) returns true

$x = 2;
$y = 3;
echo ( ($x > 1) & & ($x < 5) ) . < br / > ; // Displays 1 (true)
echo ( ($x == 2) or ($y == 0) ) . < br / > ; // Displays 1 (true)

echo ( !($x == 5 ) ) . < br / > ; // Displays 1 (true) because


// $x does not equal 5
16
Common string operators
The Concatenation Operator
<?
There is only one string operator in PHP. $txt1="Hello World!";
The concatenation operator (.) is used to put two $txt2="What a nice day!";
string values together. echo $txt1 . " " . $txt2;
?>
To concatenate two string variables together, use
the concatenation operator:
<?
strlen() function echo strlen("Hello world!");
The strlen() function is used to return the length ?>
of a string.
strpos() function
<?
The strpos() function is used to search for echo strpos("Hello
character within a string. world!","world");
If a match is found, this function will return the ?>
position of the first match. If no match is found, it
will return FALSE. 17
Understanding Operator Precedence
Consider the following example:
3+4*5
Is PHP supposed to add 3 to 4 to produce 7, then multiply the
result by 5 to produce a final figure
of 35?
Or should it multiply 4 by 5 first to get 20, then
add 3 to make 23?
All PHP operators are ordered according to
precedence. An operator with a higher
precedence is executed before an operator with
lower precedence.
In the case of the example, * has a higher precedence
than + , so PHP multiplies 4 by 5 first, then adds 3 to the result to
get 23.
18
Constants
To define a constant, use the define() function, and include inside the
parentheses the name you ve chosen for the constant, followed by
the value for the constant, as shown here:
define( MY_CONSTANT, 19 ); // MY_CONSTANT always has the string
value 19
echo MY_CONSTANT; // Displays 19 (note this is a string, not an integer)

19
Calculate the Properties of a Circle
Given that radius of a circle is 4,calculate the following:
Diameter of circle
Circumference of circle
Area of circle
HINT: use pow() function and assume PI has a value of 3.14

20
Calculate the Properties of a Circle
< ?php
$radius = 4;
$diameter = $radius * 2;
$circumference = M_PI * $diameter;
$area = M_PI * pow( $radius, 2 );
echo This circle has... < br / > ;
echo A radius of . $radius . < br / > ;
echo A diameter of . $diameter . < br / > ;
echo A circumference of . $circumference . < br / > ;
echo An area of . $area . < br / > ;
?>

21
PHP Global Variables
In contrast to local variables, a global variable can be accessed in any
part of the program.
In order to be modified, a global variable must be explicitly declared
to be global in the function in which it is to be modified.
This is accomplished, conveniently enough, by placing the keyword
GLOBAL in front of the variable that should be recognized as global.
<?
$somevar = 15;
function addit() {
GLOBAL $somevar;
$somevar++;
print "Somevar is $somevar";
}
addit();
?>
22
PHP Static Variables
In contrast to the variables declared as function parameters, which
are destroyed on the function's exit, a static variable will not lose its
value when the function exits and will still hold that value should the
function be called again.
A variable can be declared to be static simply by placing the keyword
STATIC in front of the variable name.
<?
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "
";
}
keep_track();
keep_track();
keep_track();
?> 23
Exercises:
1. Write a script that creates a variable and assigns an integer value to
it, then adds 1 to the variable s value three times, using a different
operator each time. Display the final result to the user.
2. Write a script that generates a random integer and reports whether
it is divisible by 2, by 3, or by 5.
3. Write a PHP script that reads three strings interactively and then
prints them in order of their lengths.

24

Você também pode gostar