PHP Constants:: Referenced Without $
PHP Constants:: Referenced Without $
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
// html body
</body>
</html>
PHPConstants:
- Defined near thetop of the PHP file
- Once defined, it can’t be redefined or reassigned to another value
- After definition, referenced without $
- uppercase for constants is convention
define(Name, Value);
echo() function
- is used to output something that will be seen by the browser
- HTML syntaxes & Variables within are comprehended by the browser
echo("hello");
Alternate
versions
echo "hello"; all HTML syntax are comprehended by the
browser
echo ‘hello’; syntaxes including backslash ‘\’ are not
comprehended eg. \n,\t …
HTML
echo "<em> $firstName $lastName </em>";
variables
To escape characters used for syntax eg. “ $, precede with backslash ‘\’
eg. echo “ … \$ … ”
echo “ … \“ … ”
printf() function:
- allows to apply special formatting eg. specific date/time formats or number of
decimal places
if . . . else:
- if ( condition ) { … } Alternate syntax:
else if ( condition
) { … } if ( condition ) : …
else { … } else if ( condition ) : …
else: …
endif;
switch . . . case:
- switch ($artType) { Alternate syntax:
case "PT":
… switch ($artType) :
break; case "PT":
case "SC": …
… break;
break; case "SC":
default: …
… break;
} default:
…
endswitch;
for loop:
- for ($count=0; $count < 10; $count++) Alternate syntax:
{ for ($count=0;
… $count < 10;
}
$count++) :
…
endfor;
foreach:
- foreach( $menu as $plate ){ Alternate syntax:
…
} foreach( $menu as $plate ):
…
endforeach;
‣ Functions:
forces input datatype forces return datatype
function funcName(datatype $arg = value):return datatype{
…
return … ; default value
} used if value isn’t passed on
optional function call
function changeParameter(&$arg) {
…
}
Variable Scope:
- Variables defined within a function have function scope
=> accessible within the function only
- Variables defined outside a function(global scope) are NOT accessible within the
function accessed using global keyword
function testScope() {
global $count;
}
‣ Arrays:
$arr = array( … );
$arr = [ … ];
- To define new array elements:
$arr[0] = "val1"; adds at specified index, if already defined =>
overwritten
$arr[] = " val2"; adds at the index of first empty position
Associative Arrays:
- arrays with entries in ‘key => value’ format
$days = array(0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri");
Multidimensional arrays:
$2D_arr[1D_arr][ 1D_arr_index]
$month = array(
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri")
);
$month[0][3]
$month[3][2]
$aa = [
"AMZN" => ["Amazon", 234],
"APPL" => ["Apple", 342],
"MSFT" => ["Microsoft", 165]
];
$aa["MSFT"][0]
$bb = [ $
a "AMZN" => ["name" =>"Amazon",
r "price" => 234],
r "APPL" => ["name" => "Apple",
[ "price" => 342],
r "MSFT" => ["name" => "Microsoft",
o "price" => 165]
w ];
] $bb["MSFT"]["name"]
[column]
Array Functions:
- array_push()
- adds an element at the end of the array
array_push($arr, “str”)
- array_pop()
- removes an element at the end of the array
- returns the popped element
array_pop($arr)
- array_shift()
- removes an element from the beginning of the array
- returns the popped element
array_shift($foods)
- count()
- returns the number of elements in array
count($arr)
- array_values()
- return an array containing values of an array
- can be used to remove gaps from arrays
array_values($arr)
- array_keys()
- return an array containing keys of an array
array_keys($arr)
- unset()
- used to delete an element of an array
- leaves a gap behind on the position deleted from
unset($arr[index]);
- isset()
- returnsTRUE if index is occupied
- can be used to check HTML form inputs
isset($arr[index]);
- print_r()
- displays the array structure and the values of each element in the array
print_r($arr)
Array ( [0] => apple, [1] => banana, [2] => cherry )
- extract()
- creates variables from array
- keys arethe variables names
- values of keys are values of the variables
$arr array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($arr);
$a = “Cat”
$b = "Dog"
$c = "Horse"
‣ Operators:
Mathematical Operators
- Addition +
- Subtract –
- Multiplication *
- Division /
- Power **
- Modulus %
Logical Operators:
- AND && :
- OR || :
- NOT ! :
Inc/Dec Operators
- Increment
- counter++;
- counter+=2;
- Decrement
- counter--;
- counter-=2;
‣ Mathematical Functions:
- abs($a)
- round($a)
- ceil($a)
- floor($a)
- sqrt($a)
- pow($a,$b)
- max($a,$b,…)
- min($a,$b,…)
- pi()
- rand(min,max)
‣ String Functions:
strlen()
- used to get the string length
strlen($str);
implode()
- returns a string from the elements of an array.
implode(delimeter,array)
eg implode(“ ”, $arr)
explode()
- function breaks a string into an array at specified delimeter
explode(delimeter,$str)
eg explode(“ ”, $arr)
trim()
- removes any whitespaces from the edges
- removes chars of2nd arg if they exist at the edges
optional
- breaks on first mismatch
trim($str,$chars)
eg. trim($username)
trim($username, $replace)
str_replace()
str_replace($find,$replace,$str)
preg_match()
- function returns whether a match was found in a string.
- Uses regular expressions Case insensitive
$pattern = "/Farah/i";
preg_match($pattern, $str);
Md5()
- calculates the MD5 hash of a string
- uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm
md5($str);
htmlentities()
- converts string into HTML entities if possible
htmlentities($str);
header()
die()
‣ Include files:
- PHP uses special predefined associative arrays called superglobal arrays that allow the
programmer to easily access HTTP headers, query string parameters, and other
commonly needed information
- The $_GET and $_POST arrays allow the programmer to access data sent by the
client through forms
- If form’s method is ‘GET’ then data can be retrieved from $_GET array and likewise
for ‘POST’ form method and $_POST array
- data is formatted such that: name of the form field is the key and value of the field is the
value at the key
key => value
name => value
OR user input if text
<input type=“…” name=“…” value=“…” />
- Data is accessed using field name
eg. $_GET[“name”]
$_POST[“password”]
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ( isset($_POST["uname"]) && isset($_POST["pass"]) ) {
// process data
}
}
‣ Classes:
class className {
private $firstName;
visbility public $lastName;
}
$this->localVar1 = $arg1;
className
function __constructor($arg1,$arg2){ + localVar : datatype
$this->localVar1=$arg1; …
__constructor(datatype,datatype…)
… OR
} className (datatype,datatype…)
Instantiate/Create Objects
$instName = new className(“val1”, “val2”);
Methods
- Are functions associated with a class and its instances
public function methName()
visbility
…
{
Visibility
Class member (i.e., a property or method) can be public, private, or
protected(#).
function __construct( … ) {
…
self::$statVar++;
}
}
- static properties are referenced using the self:: syntax rather than $this->
- static variables are not associated with class instances
- can be accessed without any instance via className::$statVar
- Static properties & methods are globally accessible (if public)
- Static methods are called using the same double colon syntax
className::statMethName()
Inheritance
class subclass extends superclass{ … }
Outside:
$instName->baseMethod()
$instName->subMethod()
Magic Methods
- interface (but not implementation) is always defined in a class
- must writethe codethat defines what the magic function will do.
__construct(), __destruct(), __call(), __callStatic(), __get(),
__set(), __isset(), __unset(), __sleep(), __wakeup(),
__toString(), __invoke(), __set_state(), __clone(),