You are on page 1of 27

PHP Basic

Course Code: CSC 4182 Course Title: Advanced Programming In Web Technologies

Dept. of Computer Science


Faculty of Science and Technology

Lecture No: 1 Week No: 01 Semester Fall 2021-2022


:
Lecturer: RASHIDUL HASAN NABIL; rashidul@aiub.edu
Lecture Outline

1. PHP Review (Syntax)


2. Function
3. Array
4. Class in PHP
5. Object Creation in PHP
6. Object Oriented Principle
PHP Review
• PHP stand for “PHP: Hypertext Preprocessor”
• PHP is a server side scripting language.
• Scripting languages are interpreted not compiled.
• PHP is the one of the powerful server side programming languages.
• Its free to download and very much easy to learn and use.
• PHP codes are executed in server and returns plain HTML to the browser.
• For installation you can download xamp (cross platform apache mysql and php).
• Apache engine is responsible for running php scripts.
• After installing xamp the default location of your local server
Windowsdrive(C drive)XAMPP  htdocs

• For running php the files should be kept in htdocs folder and requested through
server
PHP Syntax
• The PHP file should be saved with .php extension.
• PHP scripts starts with <?php and ends with ?>
• PHP file may contain HTML tags also with PHP scripts.
• The <?php ?> tag can be placed anywhere in PHP file.
• echo keyword is used to output in HTML.
• PHP statements ends with semicolon (;).
• In PHP keywords (if, else, while, echo, PHP etc.) ,classes, functions,
user-defined functions are not case sensitive.
• PHP variable names are case-sensitive.
• PHP comments
• <?php
//single line comment
#single line comment
/*
Multi
Line comment
*/
• ?>
• PHP is a loosely typed language so we need to declare data type of
variable.
• Variables are declared with dollar ($) in PHP.
• $$var is a reference variable that stores the value of the $variable inside
it.
Functions in PHP
• In programming functions are some block of codes that to be used multiple times.
• PHP has over 1000 built in functions which can be used directly.
• User defined function declared with function keyword.
• User defined functions in PHP can be defined like below
function myfunction(parameter_list){
Statements to be executed;
}
• A function name must starts with a letter or an underscore.
• To call a function we need to call it by its name with or without parameters
(arguments).
myfunction() //calling a function
• One function can have as many arguments as you want, just separate them with a
comma.
• As PHP is loosely typed language that’s why there is no return type in function
definition but value can be returned with return keyword.
Functions in PHP
Function without parameter
(.) dot is used to concatenate in
<?php php
function print_(){ Function with return
echo "Hello World " . "<br>"; <?php
} function add($a, $b){
print_(); calling a function $c = $a + $b;
PRINT_(); Also Correct return $c;
PriNt_(); Also Correct }
?> $result = add(10,12);
?>

Function with parameter


<?php
function add($a, $b){ Variables can also be used inside
$c = $a + $b;
double quotation ("") string.
echo "The Result is $c" . "<br>";

echo "The Result is ".$c . "<br>"; Function with variable arguments


<?php
}       function add(...$ar){
add(10,12);             $c = $ar[0] + $ar[1];
?>             return $c;
      }
$result = add(10,12);
?>
Functions with default value
• When creating function its also possible to provide default value in function
argument.
• If function definition has default value then passing parameter is optional.
• If we pass values in optional parameter it will use the passed value otherwise
it will use the default value.
<?php
The passed value is 1
function myfunction ($a = 1){ The passed value is
echo "The passed value is $a <br>"; 10
}
myfunction();//calling without optional parameter
myfunction(10); //calling with optional parameter
?>
• One function can have both mandatory and optional parameter.
<?php
function myfunction($a, $b = 1){
echo "The passed value is $a and $b <br>"; The passed value is 10 and 1
} The passed value is 12 and
myfunction(10);//calling without optional parameter 12
myfunction(12,14); //calling with optional parameter
?>
Functions with variable length arguments
• PHP supports variable length arguments which means we can pass 0..n
number of arguments without explicitly defining them.
• To do so we need to use 3 consecutive dots (…) before the argument name.
• PHP 5.6 and higher supports these concept.
• The values passed can be accessed via arrays(discussed later)
<?php  
function add(...$numbers) {  
    $sum = 0;  
    foreach ($numbers as $n) {   The output is 10
        $sum += $n;  
    }  
    return $sum;  
}    
echo  "The output is ". add(1, 2, 3, 4);  
?>  
Using global variable in functions
• Variables declared outside of function body are called global variables but
these variables can not used directly inside the function like other languages.
<?php
$global_var = 100;
function myfunction ($a = 1){
echo "The passed value is $a <br>";
echo "The global variable is $global_var <br>"; //error
}
myfunction();
?>
• To use global variable you need to use global keyword in function.
<?php
$global_var = 100;
function myfunction ($a = 1){
global $global_var;
echo "The passed value is $a <br>";
echo "The global variable is $global_var <br>";
}
myfunction();
?>
Pass by value and pass by reference
• PHP allows to pass value to function by value and reference both.
• In case of PHP call by value, actual value is not modified if it is modified inside
the function.
• In case of PHP call by reference, actual value is modified if it is modified inside
the function. In such case, you need to use & (ampersand) symbol with formal
arguments. The & represents reference of the variable.
Pass by value Pass by Reference
<?php   <?php  
function pass_value($str2)   function pass_reference(&$str2)  
{   {  
    $str2 .= 'Call By Value <br>';     $str2 .= 'Call By reference <br>';
echo $str2;   echo $str2;  
}   }  
$str = 'Hello ';   $str = 'Hello ';  
pass_value($str);   pass_reference($str);  
echo $str;   echo $str;  
?>  ?> 
Hello Call By Value Hello Call By reference
Hello Hello Call By reference
Arrays in PHP
• Array is a special variable which can hold more than one value at a time.
• In php php array() function is responsible for creating array.
<?php
     $cars = array("Volvo", "BMW", "Toyota");
     echo count($cars); //count function which returns the length of array
?>
• Arrays can also be declared using [] this syntax.
         <?php
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
echo count($cars);
?>
Types of Arrays
• In PHP there are 3 types of arrays:
• Indexed arrays (indices are numeric)
• Associative arrays (indices are strings also called as keys)
• Multidimensional arrays (arrays with one or more arrays)
• Indexed arrays
$cars = array("Volvo", "BMW", "Toyota");
• Associative arrays are special type of arrays where indices are strings instead
of numbers. Indices are called as keys.
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo $age["Peter"]; //value will be 35
$age["Harry"] = "20";//assigning new value in arrays
• Multidimensional arrays holds arrays as element in each index.
$cars = array array[0][1]
(
array("Volvo",22,18), 0th Index
array("BMW",15,13),
array("Saab",5,2), Way of accessing value:
array("Land Rover",17,15) 3rd Index Array_name[row]
); [column]
echo $cars[2][2]; //value is 2
Class in PHP
• In modern era of programming and software development object oriented
programming is a must for a software developer.
• Procedural programming is writing about functions (AKA. procedures) which
works on provided data.
• OOP is about creating objects which holds both data and functions.
• In procedural programming functions are dependent where in OOP variables
and functions are dependent on objects.
• There are 2 basic terminologies in OOP. Class: A template of things(objects).
Object: Instances of class.
• OOP provides a clear structure for the programs.
• OOP makes it possible to create full reusable applications with less code and
shorter development time.
Class Structure
• In PHP a class is defined by using class keyword followed by a class name and
a pair of curly {} braces.
• All the properties and methods are defined inside {}
<?php
class Sample {
  // code goes here...
}
?>
• In a class, variables are called properties and functions are called methods.
• Instances of classes are called objects.
• There could be as many numbers of objects of a class.
• For accessing objects properties and methods -> syntax is used.
object->properties;
object->method();
• this keyword is used to refer self properties and methods in class body.
$this->properties;
$this->method();
• Objects in PHP are created with new keyword followed by the class name.
• Methods in class can not be overloaded.
Access Modifiers
• Properties and methods can have access modifiers which control where they
can be accessed.
• There are 3 types of access modifiers;
• public:  the property or method can be accessed from everywhere.
• protected: the property or method can be accessed within the class and by
classes derived from that class
• private: the property or method can ONLY be accessed within the class
• The default access modifier is public. If we do not specify access modifier it
will be public.
• Classes do not have any access modifier. They are public. If we specify any
access modifier it will generate error.
public class Sample{
//will generate an error
}
• Functions without any access modifiers is public.
• Like functions if we do not specify access modifiers in variables it will
cause a error.
• Variables in class (properties) must have explicitly specified access modifiers
of using var before them.
public class Sample{
var $color;
}
Access Modifiers and Class Example
<?php
<?php
class Fruit {
class Fruit {
public $name;
  public $name;
public $color;
  protected $color;
public $weight;
  private $weight;
}
function set_name($n) {
$mango = new Fruit();
$this->name = $n;
$mango->name = 'Mango'; // OK
}
$mango->color = 'Yellow'; // ERROR
protected function set_color($n) {
$mango->weight = '300'; // ERROR
$this->color = $n;
?>
}
private function set_weight($n) {
$this->weight = $n;
}
}
$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>
Constructors and Destructors
• In php constructors and destructors are defined for a class using PHP
functions like __construct() and __destruct() .
class Sample{
function __construct(){
}
function __destruct(){
}
}
• The construct and destruct function starts with two underscores (__)!
• Constructors are used for initializing properties. Constructors can
arguments whereas destructors don’t.
• Previously constructor are defined with the name of classes like other
Object oriented languages. That’s why still php supports that form to
provide backward compatibility.
• while creating objects for a class, PHP will search for the magic method
__construct(). If not found and there is a function defined with the name of
the class, then, PHP will treat it as the constructor and will call it
automatically, for initializing object properties.
• As methods is class can not be overloaded constructs also can not be
overloaded.
Constructors and Destructors Examples
<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function __destruct() {
    echo "The fruit is {$this->name} and the color is {$this->color}.";
  }
}

$apple = new Fruit("Apple", "red");
?>
Getters and Setters
• Getters and setter are functions for accessing private and
protected properties.
<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
function set_name($name){
$this->name = $name;
}
function set_color($color){
$this->color = $color;
}
function get_name(){
return $this->name;
}
function get_color(){
return $this->color;
}
  function __destruct() {
    echo "The fruit is {$this->name} and the color is {$this->color}.";
  }
}
$apple = new Fruit("Apple", "red");
?>
Static Members
• A class can have static methods and properties which can be used without
creating object instance of a class.
• Static members are declared with static keyword.
• To access static members double colon (::) is used.
• className :: property;
• className::method();
• A class can have both static and non static members.
• A static member can be accessed from a method in the same class using the self
keyword and double colon (::)
• self::property;
• self::method();
• In terms of inheritance a static member of parent can be called using parent
keyword and double colon (::). In this case the access modifier must be public or
protected.
• parent::property;
• parent::method();
Static Members Examples
<?php Using parent in sub classes
class greeting {
<?php
public static $course = "ADV. WEB ";
class domain {
  public static function welcome() {
protected static function getWebsiteName() {
    echo "Hello World!";
return "W3Schools.com";
  }
}
}
}
extends used to inherit
// Call static members
class domainW3 extends domain {
greeting::welcome();
public $websiteName;
echo greeting::$course;
public function __construct() {
?>
$this->websiteName = parent::getWebsiteName();
Using self in other functions }
<?php }
class greeting {
public static $course = "ADV. WEB "; $domainW3 = new domainW3;
  public static function welcome() { echo $domainW3 -> websiteName;
    echo "Hello World!"; ?>
  }
public function __construct() {
self::welcome();
echo greeting::$course;
}
}
new greeting();
?>
Object Creation with and without ()
• As discussed earlier PHP objects can be created with new keyword.
• We can create object with or without () parenthesis but its better to follow
one.
• As we can not have overloaded functions in php we can not also overloaded
constructors also.
• If we have __construct() function with parameters then we need to pass
required parameters to create a object.
• If we want to pass a variable number of arguments to constructor (like
overloading) then we can use 3 dots(…) technique to pass variable number of
arguments.
• To access a class member in class body you must use $this->member. }
Object Examples
<?php
class Fruit {
public $name; //properties
public $color; Variable attributes

function __construct(...$attributes) {
//print_r($attributes);
$this->name = $attributes[0];
$this->color = $attributes[1];
}

function get_name() { //getters


return $this->name; Correct way of accessing variable inside class
}
function get_color(){
return $color; Wrong way of accessing variable inside class
}
}
$apple = new Fruit("Apple","Red"); //creating object with 2 parameters
$orange = new Fruit("Orange"); //creating object with 1 parameters
$banana = new Fruit; //creating object with no parameters
$banana->name = "Banana";
$banana->color = "Yellow";
echo $apple->get_name(). "<br>";
echo $apple->get_color(). "<br>";
echo $orange->get_name(). "<br>";
echo $banana->get_name();
?>
OO Principles

• Abstraction: Method of summarizing It summarizes the data and methods


which uses data.
• Encapsulation : Method of bringing together data (other objects) & related
functions to create an object.
• Inheritance: Group according to similar features/properties. A class is a
specification of an object and this specification can be
reused/generalized/inherited to create another specification with additional
properties for a new object.
• Polymorphism: different objects implementing an interface; Object can have
multiple states. Multiple methods of a class can be used to implement one
interface with different properties.
Books

 PHP Advanced and Object-Oriented Programming, 3rd Edition; Larry


Ullman; Peachpit, Press, 2013
 PHP Objects, Patterns and Practice, 5th Edition; Matt Zandstra; Apress,
2016
 Learning PHP, MySQL, JavaScript and CSS, 2nd Edition; Robin Nixon;
O’Reilly, 2009
 Eloquent JavaScript: A Modern Introduction to Programming; Marijn
Haverbeke; 2011
 Learning Node.js: A Hands On Guide to Building Web Applications in
JavaScript; Marc Wandschneider; Addison-Wesley, 2013
 Beginning Node.js; Basarat Ali Syed; Apress, 2014
References
1. https://www.w3schools.com/php/
2. https://www.php.net/
3. https://phppot.com/php/
Thank You!

You might also like