Download presentation
Presentation is loading. Please wait.
1
Open Source Programming
2
Topics to be Covered: Open Source Programming PHP Apache MySQL
Postgress SQL and PERL Overview of PHP, Variables, Operations, Constants, Control Structures, Arrays, Functions, Classes, Handling Files.
3
Open Source Generically, open source refers to a program in which the source code is available to the general public for use and/or modification from its original design free of charge, i.e., open. Open source code is typically created as a collaborative effort in which programmers improve upon the code and share the changes within the community. Open source sprouted in the technological community as a response to proprietary software owned by corporations.
4
Open Source Software's PHP Apache MySQL Postgres Perl
5
PHP Introduction The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications. Originally created by Rasmus Lerdorf in 1995. PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is a server side scripting language that is embedded in HTML. PHP is free software released under the PHP License. PHP can be deployed on most web servers and also as on almost every operating system and platform, free of charge.
6
Characteristics of PHP: Simplicity Efficiency Security Flexibility
PHP Introduction (Cont…) It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites. It is integrated with a number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server. PHP Syntax is C-Like. PHP supports a large number of major protocols such as POP3, IMAP, and LDAP. Characteristics of PHP: Simplicity Efficiency Security Flexibility Familiarity
7
PHP Introduction (Cont…)
Implementation language C OS Cross-platform License PHP License Filename extension .php, .phtml, .php4 .php3, .php5, .phps Website
8
Apache Introduction The Apache HTTP Server, commonly referred to as Apache, is a freely available Web server that is distributed under an "open source" license. Apache played a key role in the initial growth of the World Wide Web. Apache is developed and maintained by an open community of developers under the auspices of the Apache Software Foundation. Most commonly used on a Unix-like system, the software is available for a wide variety of operating system including Unix, FreeBSD, Linux, Solaris, Novell NetWare, OS X, Microsoft Windows, OS/2.
9
Apache Introduction (Cont…)
Developer(s) Apache Software Foundation Initial release 1995 Development status Active Written in C, Forth, XML Type Web server License Apache License 2.0 Website httpd.apache.org
10
MySQL Introduction MySQL : My Sequel is the world's second most widely used open-source relational database management system (RDBMS). The MySQL development project has made its source code available under the terms of the GNU General Public License, as well as under a variety of proprietary agreements. MySQL was owned and sponsored by a single for-profit firm, the Swedish company MySQL AB , now owned by Oracle Corporation. MySQL is a popular choice of database for use in web applications, and is a central component of the widely used LAMP open source web application software stack . LAMP is an acronym for "Linux , Apache, MySQL, Perl/PHP/Python." MySQL is also used in many high-profile, large-scale websites, including Wikipedia, Google, Facebook, Twitter, Flickr and YouTube.
11
MySQL Introduction (Cont…)
Original author(s) MySQL AB Developer(s) Oracle Corporation Initial release 23 May 1995; 18 years ago Development status Active Written in C, C++ Operating system Windows, Linux, Solaris, OS X,FreeBSD Available in English Type RDBMS License GPL or Commercial Website
12
Postgres Introduction
PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. It can handle workloads ranging from small single-machine applications to large Internet-facing applications with many concurrent users. PostgreSQL runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris), and Windows. It is free and open source software, released under the terms of the PostgreSQL License
13
Postgres Introduction (Cont…)
Developers: PostgreSQL Global Development Group Initial release May 1, 1995 Written in C Operating system Cross-platform, e.g. most Unix - like OS’s and Windows Type ORDBMS License PostgreSQL License Website
14
SQL Introduction SQL Structured Query Language is a special-purpose programming language designed for managing data held in a relational database management system (RDBMS). Originally based upon relational algebra and tuple relational calculus, SQL consists of a data definition language and a data manipulation language. The scope of SQL includes data insert, query, update and delete, schema creation and modification, and data access control. SQL was one of the first commercial languages for Edgar F. Codd's relational model, as described in his influential 1970 paper SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the International Organization for Standardization (ISO) in 1987.
15
Perl Introduction Perl is a programming language developed by Larry Wall, especially designed for text processing. It stands for Practical Extraction and Report Language. It runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. If you have basic knowledge of C or UNIX Shell then PERL is very easy to learn.
16
Perl Introduction (Cont…)
Developer Larry Wall Appeared in 1987; 28 years ago Implementation language C OS Cross-platform License GNU General Public License or Artistic License Filename extensions .pl .pm .t .pod Website
17
PHP Variables A variable can have a short name or a more descriptive name. Rules for PHP variables: A variable starts with the $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z 0-9, and _ ). Variable names are case-sensitive ($age and $AGE are two different variables).
18
<?php $x = 5; $y = 4; echo $x + $y; ?>
PHP Variables (Cont…) Example: <?php $x = 5; $y = 4; echo $x + $y; ?> PHP is a Loosely Typed Language In the example above, notice that we did not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct data type, depending on its value. In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.
19
In PHP, variables can be declared anywhere in the script.
PHP Variables (Cont…) PHP Variables Scope In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: local global static
20
PHP Variables (Cont…) A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function. <?php $x = 5; // global scope function myTest() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?>
21
PHP Variables (Cont…) A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function. <?php function myTest() { $x = 5; // local scope echo "<p>Variable x inside function is: $x</p>"; } myTest(); // using x outside the function will generate an error echo "<p>Variable x outside function is: $x</p>"; ?>
22
PHP Variables (Cont…) Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job. To do this, use the static keyword when you first declare the variable: <?php function myTest() { static $x = 0; echo $x; $x++; } myTest(); myTest(); myTest(); ?>
23
PHP Variables (Cont…) The global keyword is used to access a global variable from within a function. To do this, use the global keyword before the variables (inside the function): Example <?php $x = 5; $y = 10; function myTest() { global $x, $y; $y = $x + $y; } myTest(); echo $y; // outputs 15 ?>
24
PHP Data Types Variables can store data of different types, and different data types can do different things. PHP supports the following data types: String Integer Float Boolean Array Object NULL Resource
25
A string is a sequence of characters, like "Hello world!".
PHP Data types (Cont…) A string is a sequence of characters, like "Hello world!". A string can be any text inside quotes. You can use single or double quotes: Example: <?php $x = "Hello world!"; $y = 'Hello world!'; echo $x; echo "<br>"; echo $y; ?>
26
PHP Data types (Cont…) The following functions can be applied on strings: echo strlen("Hello world!"); // outputs 12 echo str_word_count("Hello world!"); // outputs 2 echo strrev("Hello world!"); // outputs !dlrow olleH echo strpos("Hello world!", "world"); // outputs 6 echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
27
An integer is a whole number (without decimals). Rules for integers:
PHP Data types (Cont…) Integer: An integer is a whole number (without decimals). Rules for integers: An integer must have at least one digit (0-9) . An integer cannot contain comma or blanks. An integer must not have a decimal point. An integer can be either positive or negative. In the following example $x is an integer. The PHP var_dump() function returns the data type and value. <?php $x = 100; var_dump($x); ?>
28
In the following example $x is a float.
PHP Data types (Cont…) Float: A float (floating point number) is a number with a decimal point or a number in exponential form. In the following example $x is a float. The PHP var_dump() function returns the data type and value. Example: <?php $x = ; var_dump($x); ?>
29
A Boolean represents two possible states: TRUE or FALSE.
PHP Data types (Cont…) Boolean: A Boolean represents two possible states: TRUE or FALSE. $x = true; $y = false; Booleans are often used in conditional testing. PHP Array: An array stores multiple values in one single variable. In the following example $cars is an array. The PHP var_dump() function returns the data type and value. Example: <?php $cars = array("Volvo","BMW","Toyota"); var_dump($cars); ?>
30
Null is a special data type which can have only one value: NULL.
PHP Data types (Cont…) NULL Value: Null is a special data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it. Tip: 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: Example: <?php $x = "Hello world!"; $x = null; var_dump($x); ?>
31
Operators Operators are used to perform operations on variables and values. PHP language supports following type of operators: Arithmetic operators Assignment operators Comparison operators Increment/Decrement operators Logical operators String operators Array operators
32
The PHP arithmetic operators are used with numeric values to
Operators (Cont…) Arithmetic Operators The PHP arithmetic operators are used with numeric values to perform common arithmetical operations.
33
The PHP assignment operators are used with numeric values to
Operators (Cont…) Assignment Operators The PHP assignment operators are used with numeric values to write a value to a variable. The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the assignment expression on the right.
34
The PHP comparison operators are used to compare two values
Operators (Cont…) Comparison Operators The PHP comparison operators are used to compare two values (number or string).
35
Operators (Cont…) Example 1: <?php $x = 100; $y = "100"; var_dump($x = = = $y); // returns false because types are not equal ?> Example 2: <?php $x = 100; $y = "100"; var_dump($x != = $y); // returns true because types are not equal ?>
36
Increment / Decrement Operators
Operators (Cont…) Increment / Decrement Operators The PHP increment operators are used to increment a variable's value. The PHP decrement operators are used to decrement a variable's
37
The PHP logical operators are used to combine conditional statements.
Operators (Cont…) Logical Operators The PHP logical operators are used to combine conditional statements.
38
PHP has two operators that are specially designed for strings.
Operators (Cont…) String Operators PHP has two operators that are specially designed for strings.
39
The PHP array operators are used to compare arrays.
Operators (Cont…) Array Operators The PHP array operators are used to compare arrays.
40
Operators (Cont…) Example 1: <?php $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); var_dump($x == $y); ?> Example 2: <?php $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); var_dump($x === $y); ?> Example 3: <?php $x = array("a" => "red", "b" => "green"); $y = array("c" => "blue", "d" => "yellow"); print_r($x + $y); // union of $x and $y ?>
41
Constants A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Unlike variables, constants are automatically global across the entire script. By default a constant is case-sensitive. To define a constant, use define() function and to retrieve the value of a constant, you have to simply specifying its name. The function constant() is used to read a constant's value if you wish to obtain the constant's name dynamically.
42
Constants (Cont…) Creating a constant: To create a constant, use the define() function. define (name, value, case-insensitive); Parameters: name: Specifies the name of the constant. value: Specifies the value of the constant. case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false.
43
Constants (Cont…) The example below creates a constant with a case-sensitive name: <?php define ("GREETING", "Welcome to PHP!"); echo GREETING; ?> The example below creates a constant with a case-insensitive name: <?php define ("GREETING", " Welcome to PHP!", true); echo greeting; ?>
44
Constants (Cont…) constant() function: As indicated by the name, this function will return the value of the constant. <?php define("MINSIZE", 50); echo MINSIZE; echo constant("MINSIZE"); // same thing as the previous line ?>
45
Constants (Cont…) Constants are Global: Constants are automatically global and can be used across the entire script. The example below uses a constant inside a function, even if it is defined outside the function. <?php define ("GREETING", "Welcome to PHP!"); function myTest() { echo GREETING; } myTest(); ?>
46
Constants (Cont…) Differences between constants and variables are: 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.
47
Control Structures Conditional statements are used to perform different actions based on different conditions. Conditional Statements In PHP we have the following conditional statements: if statement - executes some code only if a specified condition is true. if...else statement - executes some code if a condition is true and another code if the condition is false. if...elseif....else statement - specifies a new condition to test, if the first condition is false. switch statement - selects one of many blocks of code to be executed.
48
Control Structures (Cont…)
The if Statement The if statement is used to execute some code only if a specified condition is true. if (condition) { code to be executed if condition is true; } The if...else Statement Use the if....else statement to execute some code if a condition is true and another code if the condition is false. if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
49
Control Structures (Cont…)
The if...elseif....else Statement Use the if....elseif...else statement to specify a new condition to test, if the first condition is false. if (condition) { code to be executed if condition is true; } elseif (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
50
Control Structures (Cont…)
switch Statement The switch statement is used to perform different actions based on different conditions. Use the switch statement to select one of many blocks of code to be executed. switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; case label3: code to be executed if n=label3; break; ... default: code to be executed if n is different from all labels; }
51
Control Structures (Cont…)
Example: <?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, or green!"; } ?>
52
Control Structures (Cont…)
In PHP, we have the following looping statements: while - loops through a block of code as long as the specified condition is true. do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true. for - loops through a block of code a specified number of times. foreach - loops through a block of code for each element in an array.
53
Control Structures (Cont…)
while loop The while loop executes a block of code as long as the specified condition is true. while (condition is true) { code to be executed; } do...while loop The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. do { code to be executed; } while (condition is true);
54
<?php $x = 1; while($x <= 5)
Control Structures (Cont…) Example 1: <?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?> Example 2: <?php $x = 1; do { echo "The number is: $x <br>"; $x++; }while ($x <= 5); ?>
55
Control Structures (Cont…)
for loop for (init counter; test counter; increment counter) { code to be executed; } Parameters: init counter: Initialize the loop counter value. test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. increment counter: Increases the loop counter value. <?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?>
56
Control Structures (Cont…)
foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. foreach ($array as $value) { code to be executed; } For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
57
foreach ($numbers as $value) { echo $value."<br>"; } ?>
Control Structures (Cont…) Example: 1 <?php $numbers = array(1,2,3,4,5,6,7,8,9,10); foreach ($numbers as $value) { echo $value."<br>"; } ?> Example: 2 <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?>
58
Arrays An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars1 = "Volvo"; $cars2 = "BMW"; $cars3 = "Toyota"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is to create an array! An array can hold many values under a single name, and you can access the values by referring to an index number.
59
Arrays (Cont…) Create an Array in PHP: In PHP, the array() function is used to create an array. In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index Associative arrays - Arrays with named keys Multidimensional arrays - Arrays containing one or more arrays
60
Arrays (Cont…) Indexed Arrays: There are two ways to create indexed arrays: The index can be assigned automatically (index always starts at 0), like this: $cars = array("Volvo", "BMW", "Toyota"); or the index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota";
61
Arrays (Cont…) The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values: <?php $cars = array("Volvo", "BMW", "Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?> The count() function is used to return the length (the number of elements) of an array: <?php $cars = array("Volvo", "BMW", "Toyota"); echo count($cars); ?>
62
Arrays (Cont…) To loop through and print all the values of an indexed array, you could use a for loop, like this: <?php $cars = array ("Volvo", "BMW", "Toyota"); $arrlength = count ($cars); for ($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>"; } ?>
63
Arrays (Cont…) Associative Arrays: Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array: $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); or: $age['Peter'] = "35"; $age['Ben'] = "37"; $age['Joe'] = "43"; The named keys can then be used in a script: <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?>
64
Arrays (Cont…) To loop through and print all the values of an associative array, you could use a foreach loop, like this: <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?>
65
Arrays (Cont…) Multidimensional Arrays A multidimensional array is an array containing one or more arrays. Two-dimensional Arrays A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays). First, take a look at the following table: Name Stock Sold Volvo BMW Saab 5 2 Land Rover
66
Arrays (Cont…) We can store the data from the table above in a two-dimensional array, like this: $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column. To get access to the elements of the $cars array we must point to the two indices (row and column):
67
Arrays (Cont…) <?php echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>"; echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>"; echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>"; echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>"; ?> <?php for ($row = 0; $row < 4; $row++) { for ($col = 0; $col < 3; $col++) { echo "$cars[$row][$col]"; } } ?>
68
Arrays (Cont…) <?php $marks = array( "mohammad" => array
( "physics" => 35, "maths" => 30, "chemistry" => 39 ), "qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ), "zara" => array ( "physics" => 31, "maths" => 22, ) ); /* Accessing multi-dimensional array values */ echo "Marks for mohammad in physics : " ; echo $marks['mohammad']['physics'] . "<br />"; echo "Marks for qadir in maths : "; echo $marks['qadir']['maths'] . "<br />"; echo "Marks for zara in chemistry : " ; echo $marks['zara']['chemistry'] . "<br />"; ?>
69
Functions PHP functions are similar to other programming languages.
A function is a block of statements that can be used to perform a specific task. User Defined Functions: Besides the built-in PHP functions, we can create our own functions. A user defined function declaration starts with the word "function": Syntax function functionName() { code to be executed; }
70
In the example below, we create a function named "writeMsg()".
Functions (Cont…) In the example below, we create a function named "writeMsg()". The opening curly brace { indicates the beginning of the function code and the closing curly brace } indicates the end of the function. The function outputs "Hello world!". To call the function, just write its name. <?php function writeMsg() { echo "Hello world!"; } writeMsg(); // call the function ?>
71
Information can be passed to functions through arguments.
Functions (Cont…) Function Arguments: Information can be passed to functions through arguments. An argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma operator. <?php function familyName($fname) { echo "$fname Refsnes.<br>"; } familyName("Jani"); familyName("Hege"); familyName("Stale"); familyName("Kai Jim"); familyName("Borge"); ?>
72
Default Argument Value:
Functions (Cont…) <?php function familyName($fname, $year) { echo "$fname Refsnes. Born in $year <br>"; } familyName("Hege", "1975"); familyName("Stale", "1978"); familyName("Kai Jim", "1983"); ?> Default Argument Value: The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument. <?php function setHeight($minheight = 50) { echo "The height is : $minheight <br>"; } setHeight(350); setHeight(); // will use the default value of 50 ?>
73
Functions - Returning values:
Functions (Cont…) Functions - Returning values: A function can return a value using the return statement. Return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(1,2,3,4). <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; return $sum; } $return_value = addFunction(10, 20); echo "Returned value from the function : $return_value"; ?>
74
Functions - Returning values:
Functions (Cont…) Functions - Returning values: A function can return a value using the return statement. Return stops the execution of the function and sends the value back to the calling code. You can return more than one value from a function using return array(1,2,3,4). <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; return $sum; } $return_value = addFunction(10, 20); echo "Returned value from the function : $return_value"; ?>
75
function calc($num1, $num2, $op) { switch ($op) { case "+":
<?php function calc($num1, $num2, $op) { switch ($op) { case "+": $total = $num1 + $num2; return $total; break; case "-": $total = $num1 - $num2; case "*": $total = $num1 * $num2; case "/": $total = $num1 / $num2; default: echo "Unknown operator."; } echo calc(10,10,"+"); ?> Functions (Cont…)
76
Classes Object Oriented Concepts:
Class: This is a programmer-defined data type, which includes local functions as well as local data. A class acts as a template for making many instances of the same kind (or class) of object. Object: An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance. Member Variable: These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. Member function: These are the function defined inside a class and are used to access object data.
77
Inheritance: Acquiring properties from one class to another class is
Classes (Contd…) Inheritance: Acquiring properties from one class to another class is called an inheritance. Parent class: A class that is inherited from by another class. This is also called a base class or super class. Child Class: A class that inherits from another class. This is also called a subclass or derived class. Polymorphism: This is an object oriented concept where same function can be used for different purposes. Overloading: A type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
78
Data Abstraction: Any representation of data in which the
Classes (Contd…) Data Abstraction: Any representation of data in which the implementation details are hidden (abstracted). Encapsulation: Refers to a concept where we encapsulate all the data and member functions together to form an object. Constructor: Refers to a special type of function which will be called automatically whenever there is an object formation from a class. Destructor: Refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.
79
The general form for defining a new class in PHP is as follows:
Classes (Contd…) Defining PHP Class: The general form for defining a new class in PHP is as follows: <?php class phpClass { var $var1; var $var2 = "constant string"; function myfunc ($arg1, $arg2) //Code to be included here } ?>
80
The special form class, followed by the name of the class that
Classes (Contd…) The special form class, followed by the name of the class that you want to define. A set of braces enclosing any number of variable declarations and function definitions. Variable declarations start with the special form var, which is followed by a conventional $ variable name. Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.
81
function setPrice($par){ $this->price = $par; }
Classes (Contd…) Example: <?php class Books{ /* Member variables */ var $price; var $title; /* Member functions */ function setPrice($par){ $this->price = $par; } function getPrice(){ echo $this->price ."<br/>"; function setTitle($par){ $this->title = $par; function getTitle(){ echo $this->title ." <br/>"; ?> The variable $this is a special variable and it refers to the current object.
82
Creating Objects in PHP:
Classes (Contd…) Creating Objects in PHP: Once you defined your class, then you can create as many objects as you like of that class type. $objectname = new classname; Following is an example of how to create object using new operator. $physics = new Books; $maths = new Books; $chemistry = new Books; Here we have created three objects and these objects are independent of each other and they will have their existence separately. These objects are used to access member function and member variables.
83
Calling Member Functions:
Classes (Contd…) Calling Member Functions: After creating your objects, you will be able to call member functions related to that object. $objectname -> functionname (parameters list ); Following example shows how to set title and prices for the three books by calling member functions. $physics->setTitle( "Physics for High School" ); $chemistry->setTitle( "Advanced Chemistry" ); $maths->setTitle( "Algebra" ); $physics->setPrice( 10 ); $chemistry->setPrice( 15 ); $maths->setPrice( 7 ); $physics->getTitle(); $chemistry->getTitle(); $maths->getTitle(); $physics->getPrice(); $chemistry->getPrice(); $maths->getPrice();
84
A class can inherit properties from another class by using
Classes (Contd…) Inheritance: A class can inherit properties from another class by using the extends clause. The syntax is as follows: class Child extends Parent { <definition body> } The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics: Automatically has all the member variable declarations of the parent class. Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.
85
Following example inherit Books class and adds more
Classes (Contd…) Following example inherit Books class and adds more functionality based on the requirement. class Novel extends Books{ var publisher; function setPublisher($par){ $this->publisher = $par; } function getPublisher(){ echo $this->publisher. "<br />";
86
Function definitions in child classes override definitions
Classes (Contd…) Function Overriding: Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class. In the follwoing example getPrice and getTitle functions are overriden to retrun some values. function getPrice(){ echo $this->price . "<br/>"; return $this->price; } function getTitle(){ echo $this->title . "<br/>"; return $this->title;
87
Unless you specify otherwise, properties and methods of a
Classes (Contd…) Public Members: Unless you specify otherwise, properties and methods of a class are public. If you wish to limit the accessibility of the members of a class then you define class members as private or protected. Private members: By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class. A class member can be made private by using private keyword in-front of the member.
88
function _construct($par) { // Statements here run every time
Classes (Contd…) Example: class MyClass { private $car = "skoda"; $driver = "SRK"; function _construct($par) { // Statements here run every time // an instance of the class // is created. } function myPublicFunction() { return("I'm visible!"); private function myPrivateFunction() { return("I'm not visible outside!");
89
A protected property or method is accessible in the class in
Classes (Contd…) Protected members: A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in-front of the member. class MyClass { protected $car = "skoda"; $driver = "SRK"; function __construct($par) { // Statements } function myPublicFunction() { return("I'm visible!"); protected function myPrivateFunction() { return("I'm visible in child class!");
90
Interfaces are defined to provide a common function names
Classes (Contd…) Interfaces: Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are Skelton's which are implemented by developers. interface Mail { public function sendMail(); } class Report implements Mail { // sendMail() Definition goes here
91
A constant is somewhat like a variable, in that it holds a
Classes (Contd…) Constants: A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change. class MyClass { const requiredMargin = 1.7; function _construct ($incomingValue) { // Statements here run every time // an instance of the class is created. } In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7.
92
An abstract class is one that cannot be instantiated, only inherited.
Classes (Contd…) Abstract Class: An abstract class is one that cannot be instantiated, only inherited. You can declare an abstract class with the keyword abstract. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility. abstract class MyAbstractClass { abstract function myAbstractFunction() { } Note that function declarations inside an abstract class must also be preceded by the keyword abstract.
93
Declaring class members or methods as static makes them
Classes (Contd…) Static Keyword: Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object. <?php class Sample { public static $my_static = ‘Hello’; public function staticValue() { return self :: $my_static; } print Sample :: $my_static . "\n"; $obj = new Sample(); print $obj -> staticValue() . "\n"; ?>
94
PHP 5 introduces the final keyword, which prevents child
Classes (Contd…) Final Keyword: PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. <?php class BaseClass { public function test() { echo "BaseClass::test() called<br>"; } final public function moreTesting() { echo "BaseClass::moreTesting() called<br>"; class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() called<br>"; ?>
95
Constructor Functions:
Constructor functions are special type of functions which are called automatically whenever an object is created. PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function. Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation. function __construct( $par1, $par2 ){ $this->price = $par1; $this->title = $par2; } Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Classes (Contd…)
96
$physics = new Books( "Physics for High School", 10 );
Classes (Contd…) $physics = new Books( "Physics for High School", 10 ); $maths = new Books ( "Advanced Chemistry", 15 ); $chemistry = new Books ("Algebra", 7 ); /* Get those set values */ $physics->getTitle(); $chemistry->getTitle(); $maths->getTitle(); $physics->getPrice(); $chemistry->getPrice(); $maths->getPrice(); Destructor: Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor.
97
File Handling File handling is an important part of any web application. You often need to open and process a file for different tasks. Procedure to handle a file: Opening a file Reading a file Writing a file Closing a file Opening and Closing Files: The PHP fopen() function is used to open a file. It requires two arguments, one is file name and the second one is mode of the file.
98
File Handling (Contd…)
If an attempt to open a file fails then fopen() returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file. After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
99
File Handling (Contd…)
Files modes can be specified as one of the six options in this table.
100
File Handling (Contd…)
Reading a file: Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes. The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes. So here are the steps required to read a file with PHP. Open a file using fopen() function. Get the file's length using filesize() function. Read the file's content using fread() function. Close the file with fclose() function.
101
File Handling (Contd…)
The following example assigns the content of a text file to a variable then displays those contents on the web page. <?php $filename = "sample.txt"; $file = fopen($filename,"r"); if($file == false){ echo ("Error in opening file"); exit(); } $size = filesize($filename); $filetext = fread($file,$size); fclose($file); echo ("File size : $size bytes"."<br>"); echo $filetext; ?>
102
File Handling (Contd…)
Writing a file: A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached. The following example creates a new text file then writes a short text heading inside it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument.
103
File Handling (Contd…)
Example: <?php $filename = "newfile.txt"; $file = fopen($filename,"w"); if($file == false ){ echo ("Error in opening new file"); exit(); } fwrite($file,"This is a simple test\n"); fclose($file); ?>
104
File Handling (Contd…)
Other file related functions: readfile() fgets() fgetc() feof() readfile() function is used to read the contents of the file. <?php echo readfile(“sample.txt"); ?> The fgets() function is used to read a single line from a file. After a call to the fgets() function, the file pointer has moved to the next line. $myfile=fopen(“sample.txt","r"); echo fgets($myfile); fclose($myfile);
105
File Handling (Contd…)
The feof() function checks if the "end-of-file" (EOF) has been reached. The feof() function is useful for looping through data of unknown length. The example below reads the “sample.txt" file line by line, until end-of-file is reached. <?php $myfile = fopen(“sample.txt", "r"); while(!feof($myfile)) { echo fgets($myfile) . "<br>"; } fclose($myfile); ?>
106
File Handling (Contd…)
The fgetc() function is used to read a single character from a file. The example below reads the “sample.txt" file character by character, until end-of-file is reached. <?php $myfile = fopen(“sample.txt", "r“); while(!feof($myfile)) { echo fgetc($myfile); } fclose($myfile); ?>
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.