0% found this document useful (0 votes)
26 views

PHP Constants:: Referenced Without $

- PHP is a server-side scripting language that can be embedded within HTML code. PHP code is written within <?php ?> tags and files have a .php extension. - Variables in PHP are dynamically typed and declared with a leading $, and can be of types like string, integer, boolean, array or object. Constants are defined with DEFINE and referenced without $. - Common output functions include echo and printf. Control structures include if/else, switch, while, for, and foreach loops. Functions can define arguments, return types, and pass by value or reference. - Arrays can be indexed, associative, or multidimensional. Common array functions are array_push, array_pop

Uploaded by

alibrahimm.farah
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)
26 views

PHP Constants:: Referenced Without $

- PHP is a server-side scripting language that can be embedded within HTML code. PHP code is written within <?php ?> tags and files have a .php extension. - Variables in PHP are dynamically typed and declared with a leading $, and can be of types like string, integer, boolean, array or object. Constants are defined with DEFINE and referenced without $. - Common output functions include echo and printf. Control structures include if/else, switch, while, for, and foreach loops. Functions can define arguments, return types, and pass by value or reference. - Arrays can be indexed, associative, or multidimensional. Common array functions are array_push, array_pop

Uploaded by

alibrahimm.farah
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/ 13

Chapter12:PHP

- PHP is written within <?php … ?> tags


- written in a file with extension .php
- PHP file can contain HTML
- any code outside PHP tags is HTML
<?php
echo “ ”;
?>

<html lang="en">
<head>
<title>Document</title>
</head>
<body>
// html body
</body>
</html>

‣ Variables & Datatypes:

- Variables are dynamically typed => no datatype declared before variables


- Variables are declared loosely => variable can be reassigned to different datatypes
- Preceded by $ on definition and on reference
- Datatypes:  boolean
 Integer
 float
 string
 Array
 Objects
$user= “Randy”;
$year = 1982;
$employed = true;
$price = 4.99;

 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);

eg. define(“PI”, 3.1415);


$area = $raduis * ( PI ** 2 );

Referenced without $
‣ Output:

 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 “ … \“ … ”

 Single quotations ‘ ’ within double quotations “ ” doesn’t need escape


eg. echo "<img src='$id.jpg' alt=' $firstName $lastName' >";

 printf() function:
- allows to apply special formatting eg. specific date/time formats or number of
decimal places

printf("The %s is %.2f pounds", $product, $weight);


placeholders same order of
Precision specifier placeholders
‣ String Concatenation:

Strings can be appended together using the concatenate operators


1- ‘ . ’
2- ‘ , ’
echo $lastName . “, ” . $firstName;
echo $lastName , “, ” , $firstName;
‣ Program Control:

 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;

 while and do . . . while:


- while ($count < 10) { Alternate syntax:

} while ($count < 10) :

endwhile;

- do {  executed atleast once



} while (condition);

 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

 Argument are passed to functions as value


=> any changes on the variable within the scope of the function isn’t reflected to the
original variable
 Passing a variableto a function as reference => any updates to the variable is also
reflected on the variable outsidethe function scope
 To pass a variable as reference:

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");

- key acts as index


$arr[key] = value;  to define
$arr[key]  to reference

 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]

 Iterating through Array:


foreach ($forecast as $value) {  takes only values
echo $value . "<br>";
}

foreach ($forecast as $key => $value) {  takes keys and values


echo "day[" . $key . "]=" . $value;
}

 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);

eg. $str = '<a href="https://www.w3schools.com">


Go to w3schools.com</a>';
htmlentities($str);

 header()
 die()
‣ Include files:

- includes a Copy of the content of a file (php/html/text) in the php file


- Reduces redundancy  Sections of website become reusable eg. footer
Changes only need to be made in one place
- Syntaxes used to include files: on include error:
1. include "somefile.php"; warning is displayed then
2. include_once "somefile.php"; execution continues
File won’t be included
if already included 3. require "somefile.php";
4. require_once "somefile.php"; error is displayed and
execution stops
 by convention files to be included have ‘.inc.php’ extension to imply that this is an
include file
 Variables defined within an include file will havethe scope of the line on which the
include occurs
‣ $_GET and $_POST Superglobal Arrays:

- 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”]

 Determining If Any Data Sent:


- Same php file could be responsible for displaying form and processing input
data
- To insure that data is sent prior processing:
1- Check if a GET or POST request was requested
$_SERVER['REQUEST_METHOD']
'REQUEST_METHOD' will be either empty or contain ‘POST’/ ‘GET’
- empty indicates no request
- ‘POST’/ ‘GET’ indicates a request
issued depending on the form method.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
}

2- Check if any of the fields are set using isset() or empty()


- isset() may return true although field is empty(but not null)  “”
- better to use empty: returns true on null and on empty string “”
!empty($_POST["uname"])

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ( isset($_POST["uname"]) && isset($_POST["pass"]) ) {
// process data
}
}

‣ Classes:

class className {
private $firstName;
visbility public $lastName;
}

All variables are declared within {} beforethe constructor.


 Constructor:
- constructors are defined as functions with the name __construct() (double
underscores _)
- assign input parameters values to local variables using this-> prefix

$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”);

 Parameters of an instance can be set and accessed by:


$instName->arg1  access
$instName->arg1 = “val”;  set

 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(#).

 public(+): property/method is accessibleto any


codethat has a referenceto the object.
 private(-): sets a method or variableto only be
accessible from within the class.
 Static Members
- A property or method that all instances of a class sharethe value of
class className {
public static statVar = val ;

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{ … }

- inheriting class is said to be a subclass or a derived class.


- inherited class is a superclass or a base class
- subclass inherits all of public and protected methods and variables
- private members are not inherited
- if subclass method requires additional parameters compared to the parent class,
you can define it with these additional parameters in the subclass and overridden
- Referencing Superclass Members:
 Inside Subclass:
- any referenceto a member in the base class requires the addition of
the parent:: prefix instead of the $this->
parent::baseMethod();

 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(),

- wherever the object is echoed, it will automatically call __toString()

You might also like