Está en la página 1de 49

TPL2141 - PROGRAMMING LANGUAGE CONCEPTTPL2141 - PROGRAMMING

LANGUAGE CONCEPT
1

Description of Programming Language on C++ and PHP


1111115155 Lau Jia Quan & 1111115046 Tan Pooi Shiang
Faculty of Information Science & Technology

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

Abstract
The purpose of this report will explain the properties about C++ and PHP programming language
to understand their features and advantage on their specific fields. The report conducted to 7
parts which excluded references and appendix. This include the history, basic elements, support
programming style, unique features, current status, application domain and conclusion. Besides
that, this report is also consist as a comparison of the differentiation between C++ and PHP
programming language. This will allow for more individual to understand these two languages.
Lastly, we would like to take this opportunity to show our gratitude to my seniors and diploma
lecturers that give us a lot of suggestion for doing this report, especially to Miss Ong Lee Yeng
that brief us about the details how should be done and what kind of content should be contain in
this report.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

HISTORY OF C++ PROGRAMMING LANGUAGE


The programming language C++ (originally named called C with Classes) was created
by Bjarne Strourup, an employee from Bell Labs (AT&T) while doing his Ph.D.thesis in the
1979. At first he had experiences with the language called Simula (a slow language but had some
features that were very helpful for large software development project), which is the first
language that support the object-oriented programming paradigm and found out this paradigm is
very useful for software development. Afterwards, he chose to improve the C language with
Simula-like features to reach his ultimate goal of adding object-oriented programming into C
language which is a language still having portability while having fast speed or low-level
functionality. The first C with Class compiler was call Cfront, which derived from a C compiler
call CPre.
In 1983, the name of language C with Classes changed to C++. Besides that, First edition
of The C++ Programming Language was released,followed by the commercial release of C++
language in the October of the same year.
In 1989, version 2.0 was released of the C++ language, followed by the updated second
edition of The C++ Programming Language in 1991. A lot of new features added in 2.0 such as
multiple inheritance, abstract classes, and static member functions and so on. After the 2.0
update, there was no more any big updates for C++ until now. Just that in 2003 the committee
published a corrected version of the C++ standard.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

BASIC ELEMENTS OF THE LANGUAGE

Name
A name is usually think of identifiers but can be more general. In the C++ programming
language, an identifier is a string of characters, starting with a letter of the alphabet or an
underline. The basic rules in C++ for identifiers are:
1.
2.
3.
4.
5.
6.

Only Alphabets, Digits and Underscores are permitted.


Identifier name cannot start with a digit and no length limit.
Keywords cannot be used as a name. (final, static)
Upper case and lower case letters are distinct. (Case-sensitive)
Special Characters are not allowed
Global Identifier cannot be used as Identifier.

Valid Examples
Identifier

Note

Howei

Capital Letter and Small Letters are Allowed

hue_1

Digits and Underscore is allowed along with alphabets

_ADS

Underscore at the first position is allowed

total_of_apple

Combine multiple words with underscore are allowed

INT

Keywords are allowed but have to change case of any letter

printf

printf is allow if not include stdio.h header file

Invalid Examples
Identifier

Note

3cars

Digits are not allowed in the first letter

Ali^2

Special character are not allow

$friend

$ is not support by C++

John smith

Spaces are not allowed in C++

float

Keywords are not allowed

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

Variables
A variable provide us a named storage for any value that allow programs to manipulate.
Variable can be declared in many ways with different memory requirements and functioning.
Besides that, variable is the name of memory location allocated by the compiler depending upon
the data type of the variable.

Variable must be declared before they can be used. Usually it is advised to declare them
at the starting of the program, but in C++ they can be declared in the middle of program too.
Example:
int main(){
int I;
char c;
float I, j ,k;
}

//declared but no initialized


//initialized again
//multiple declaration

Initialization means assigning value to an already declared variable.


int main(){
int I;
I = 10;
}

//declaration
//initialization

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

Initialization and declaration can be done in one single step also.


int main(){
int I =10;
}

//declaration and initialization in same step

If a variable is declared and not initialized by default it will hold a garbage value. Also, if a
variable is once declared and if try to declare it again, we will get a compile time error.
int main(){
int I,j;
initialized
I = 10;
j = 20;
int j = I + j;
//compile time error,
//cannot redeclare a variable in same scope
}

Binding
A binding is an association between an entity and an attribute such as between an
operation and a symbol. In C++, binding means the process of converting identifiers (such as
variables and function names) into machine language addresses. Mostly binding are use on
functions. There are two different type of binding, which is static binding and dynamic binding.
Static binding (also called early binding) means that compiler able to associate the
identifier name with a machine address directly. This is mostly used on direct function calls. So
when compiler encounter a function call, it replace the function with a machine language
instruction that tell the CPU to jump to the address of the function. Here is an example of direct
function call.
void PrintResult(int result){
std::cout<<result;
}
int main(){
PrintResult(5);
//this is a direct function call
}

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

Dynamic binding (also known as late binding) means that some programs may not know
which function will be call until runtime. So in C++, it normally happens when the virtual
keyword is used in method declaration.
Class B{
public:
virtual void f();
};
void B::f(){
cout <<B::f();<<endl;
}

In C++ dynamic binding function calls, one way to get dynamic binding is using function
pointers.
int add(int x,int y){
return x+y;
}
int main(){
int (*padd)(int,int)=add;
//create a function pointer for add function
Cout << padd(4,4) <<endl; //add 4+4
}

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

Built-in and user-defined data type


Each variable has a specific type to determine the size and layout of the variable's
memory, the range of values that can be stored in the memory and the set of operations that can
be applied.
Following are the basic built-in data types in C++:
Basic type of variables in C++
Type

Description

bool

Store the value true or false only.

int

Store integer character

char

Character or very short integer

float

A single-precision floating point value

double

A double-precision floating point value

void

Represent absence of type

wchar_t

A wide character type

Now we have already know the basic of the C++ data types. But in addition of these, there are
other kinds of user-defined data types.
Typedef, C++ allows us to define our own types based on other existing data types which in the
form of:
typedef existing_type new_type name;
Where existing_type is a C++ fundamental or other defined type and new_type name is the name
of the new type we going to declare. For example:
typedef
typedef
typedef
typedef

double B;
int number;
char A;
char are[30];

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

Union allow a portion of memory to be accessed as different date types since all of them
are in the same memory location. Its declaration form is :
union model_name{
type1 element1;
type 2 element2;
.
}object_name;

All of the elements inside union occupy the same space of memory. Its size is one of the greatest
elements in the declarations. Example:
union mytype_e{
char c;
int f;
}mytype
Scope
All variables has their area of functioning, and out of that boundary they cant hold their
value. This boundary is called scope of variable. Its restrict the variable visibility and usability
Therefore, we can conclude that scoping has to do with the accessibility and usability of a
variable. There are two types of scope which is outer scope and inner scope.

Outer scope are mostly where global variables declared which is often declared outside
of main() function. The benefits for declaring like this is they can be assigned different values at
different time in program accessed by any functions or any class. For example:
#include <iostream>
using namespace std;
int x;
//global variable declared
int main(){
x=10;
//initialized once
cout << x << endl;
x=15;
//initialized again
cout << x << endl;}

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

10

Inner scope is where local variables are declared, which is between the curly bracers and
exist inside within them only. It cannot be accessed in the outer scope. For example:
int main()
{
int i=20;
if(i<20)
{
int n = 100; //local variable declared and initialized
cout << n << endl; //print 100
}
cout << n << endl; //error, n not available at here
}

Lifetime of a variables or objects


The lifetime of a variables is the location where variables exists as in variables are being
created and destroyed while the program is running. Which mean that programming language
will need to let the program create new variables when needed, also delete them when they are
not needed. Therefore, a variable has a lifetime. After that, there are rules apply on C++ lifetime,
a variable begin to exist when defined and stop to exist at the end of the scope of the variable is
defined. Lastly, Lifetime are apply on local and global variables only but with different
condition.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

11

Local variables, lifetime of existence start only after its definition and ended when it is
outside of the scope it is in shown in the example below.
float f(float x)
{
... CANNOT access any variable
int var3;
<--------- var3 starts to exist
.. var3 accessible
{
.. var3 accessible
float var4;
<--- var4 starts to exist
var3 and var4 are accessible
}
<--- var4 ends to exist
.. only var3 accessible...
}
<--------- var3 ends to exist

Global variables can be define outside of any functions which make lifetime of its
existence start when the program starts and end when program exit shown in the example below.
{
int x; < - - global variable start to exist
int main(int argc, char **argv)
{
....< - - x accessible
}
float f(float x)
{
....<---- x accessible
}
} < - - x ends to exist

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

12

Referencing Environment
Referencing Environment of a statement is refer to the collection of names that are
visible. Inside C++ there is a feature call reference to perform this task. A reference is another
name of an existing variable by using & as a declarations. The variable name or the reference
name may use to refer variable when only a reference is initialized with a variable.
int main ()
{
// declare simple variables
int

i;

double d;

// declare reference variables


int&

r = i;

double& s = d;

i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;

d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;

Output:
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

13

SUPPORTED PROGRAMMING STYLE OF C++


C++ programming language support more than one programming style, those styles
included imperative programming, object-oriented programming, functional programming, logic
programming and scripting programming.
Object-oriented programming is supported because C++ view a problem in terms of
objects involved rather than the procedure for doing it. An object is an identifiable entity with
characteristics and behaviours, which mean object represent an entity that store data and has its
interface through functions. Below is a sample example is written in object-oriented in C++.
include <iostream>
class Counting {
private :
int a,b,ans;
public :
int & GetNum1() {
return this->a;
}
int & GetNum2() {
return this->b;
}
int & GetAns(){
return this->ans;
}
void SetNum1(int a){
this.a = a;
}
void SetNum2(int b){
this.b = b;
}
void Calculate(char c) {
switch(c){
case +:
ans = a + b;break;
case -:
ans = a b;break;
case *:
ans = a * b;break;
case /:
ans = a * b;break;
default;
break;
}
}
};
using namespace std;

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

14

int main(int argc, char *argv[])


{
Counting calc;
cout << Calculator\n;
cout << First number:;
cin << calc.GetNum1();
cout << Second number:;
cin << calc.GetNum2();
calc.Calculate(+):
cout << calc.GetNum1() << + << calc.GetNum2() << =;
cout << calc.GetAns();
}

Above source code show that there is a class call Calculator and implement its addition
operation. Not only that, the code also extended this class to support other operations like
multiple, division and subtract.

Imperative programming are issuing commands, telling the computers what to do. To
be more specific is to be list of instructions. Upon done performing the instructions the result
will be produced. Below is a loop example.
include <stdio.h>
using namespace std;
int main()
{
Int value = 1;
While(value <= 3)
{
Printf(Value %d\n, value);
Value++;
}
}
Output:
Value 1
Value 2
Value 3

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

15

Functional Programming. Besides of providing a huge functions library, main reason is


because C++ recently has a new feature that support Lambda functions. A Lambda function is a
function that you can write inline in your source code, similar to the idea of function pointer.
With lambda, creating quick functions has become much easier. Below is an example of basic
lambda syntax.
#include <iostream>
using namespace std;
int main()
{
auto func = [] () { cout << "Hello world"; };
//[] means lambda function created
func(); // now call the function
}

Logic programming by using LC++ which is a library preserves the expression syntax
of logic programming like Prolog but also added C++ static type checking and arbitrary effect
features. By using LC++, C++ programmers can write declarative, Prolog-like code in C++
programs. Sample codes as shown below.
Here is how we declare the type of functors/relations.
FUN2(parent,string,string)
FUN2(father,string,string)
FUN2(mother,string,string)
FUN2(child,string,string)
FUN1(male,string,string)
FUN1(female,string,string)
Here is how we declare logic variables.
DECLARE(Mom, string,0)
DECLARE(Dad, string,1)
DECLARE(Bro, string,2)
DECLARE(Sis, string,3)
DECLARE(Kid, string,4)
DECLARE(X, int,10)
DECLARE(Y, int,11)

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

16

Scripting language was apply on C++ due to the update of C++ 11 that focus on usable
library, value types and other. Using C++ as a scripting language has a lot of advantages like
memory leaks wont happen, faster than any non-JITted scripting language, every line of code is
clear, understandable and expressive. Below is a sample code that read all lines from a file and
write them into another file in sorted order.
#include<string>
#include<vector>
#include<algorithm>
#include<fstream>
usingnamespacestd;
intmain(intargc,char**argv){
ifstreamifile(argv[1]);
ofstreamofile(argv[2]);
stringline;
vector<string>data;
while(getline(ifile,line)){
data.push_back(line);}
sort(data.begin(),data.end());
for(constauto&i:data){
ofile<<i<<std::endl;
}

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

17

return0;}

DISTINCT FEATURES OF C++


What are unique features of C++ that distinguish itself from other languages?
Firstly will be the performance. Its really hard to think have other languages that can
create a program that is fast in performance. Furthermore, low-level features of C++ let us write
programs interacting directly with hardware so it makes C++ still is kings of embedded
programming. After that, C++ provide powerful abstractions, in particular the ability to write
generic code that is better among Java and C#. All about features makes C++ is a better choice of
developing huge operating system because operating systems are huge programs that need to be
fast and interact directly with hardware. Other than that, C++ has a convenience thing call Boost
library: Boost C++ Libraries. It has a lot of useful tools which make C++ is a useful language.
For example, support for regular expressions. Recently inside C++ 11, there is a new feature call
range-based for loops. It is used as a more readable equivalent to the traditional for loop
operating over a range of values, such as all elements in a container. For a better insight, here
you can find a better understanding about this feature Range-Based for loops.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

18

APPLICATION DOMAIN OF THE LANGUAGE


What application domain(s) is C++ designed for?
C++ provide a combination of reasonable portability. It offers easy low-level access to
machine like raw memory that supports operating systems and device driver, medium-level
capabilities such as data structuring and modularity like compilers, lastly high-level codeorganization arrangement which is object-oriented, exception handling to help control the
complexity when building large system. So mainly C++ core application domain is on system
programming. Not only that, Application domains that needs interoperability, performance,
deplorability and portability criteria that other programmer-friendly languages failed to
accomplished are C++ best fit in as well.
What type of applications is C++ being used mostly?
From the description above of what application domains that C++ good with, there are a
huge numbers of applications that are developed by C++. Most of the applications are Numerical
computations: graphical games, finance, statistics; Bit fiddling: operating systems, telecom, and
device driver development. Here is a list of companies/applications written in C++ from Bjarne
Stroustrup provide. Most common application that well-known as Adobe System, their major
applications are developed in C++ because it has the effective fast speed to control the huge data
that the system hold. For example, Photoshop and Illustrators. Besides of that, applications that
handles 3D graphics need C++ language due that C++ makes it possible for programmer to
create engines fast enough for their performance in any hard-core graphics. For example
DirectX, Doom III engine and OpenGL. Operating system applications are Microsoft (Visual C+
+), LINUX (CDE Desktop), Apple (IOS kit device drivers) and IBM. There are a few web

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

19

browsers used C++ as well which is Google and Mozilla. Lastly, MySQL the worlds most
popular open source database that contains about 250,000 lines of C++ languages.

CURRENT STATUS OF THE LANGUAGE


Is C++ currently a popular language?
The answer is yes. According to TIOBE, a webpage that accumulate which languages are
being discussed the most. C++ is currently hanging at the top 3 in the chart. Although Java sitting
the first place spot because of Java version 8 gain a great success but C++ is making a big gain
slowly. From a report we found, C++ 14, completed last year has add the ability to handle
Lambdas while inherited from C++ 11 with other improvements that in compilers as helping
language cause. Besides that, Bjarne Stroustrup said that the languages sweet spot is its ability
to handle complexity while still running fast. Not only that, there are a lot of legacy codes
written in C++. Furthermore, C++ is a flexible languages that work well in applications domains
which from video games to financial applications, categorized as commercial software
development

such

as

desktop

programs,

simulations(including games), and system software.

database

engines,

operating

system,

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

20

History of PHP
PHP is a programming language created in 1994 by Rasmus Lerdorf. At the first, PHP
was just a simple set of Common Gateway Interface(CGI) binaries written in C programming
language. Rasmus Lerdorf used it for tracking who visits to his online resume, he named the
suite of scripts as Personal Home Page Tools, also referenced as PHP Tools. In June 1995,
Rasmus going to release the source code for PHP Tools to public which allowed developers to
use it, permitted and encouraged users to provide fixes for bugs in the code.
In September 1995, new implementation included some basic functionality of
PHP such as Perl-like variables, automatic interpretation of form variables, and HTML
embedded syntax. After the implementation it was not entirely well-received. In October 1995,
Rasmus released a cpmplete rewrite code which named as Personal Home Page Construction Kit.
The language was designed like C in structure to make it easy for developers which familiar with
C, Perl, and similar languages.
In April 1996, PHP evolve from a suite of tools into a programming language. It
support for DBM, mSQL and Postgres95 databases, cookies and so on. In 1997 and 1998,
PHP/Fl had a several thousand users around the world. In May 1998, that nearly 60,000 domain
reported having headers containing PHP. This number equated to approximately 1% of all
domains on the internet at the time.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

21

Basic Element of PHP

Names
Name is a string of characters, starting with dollar sign. The basic rules in PHP for
identifiers are:
1. Variable names have to start with a dollar sign($)
Example: $variableA
2. Variable names can start with letter or underscore
Example: $VAL, $_value
3. Variable names only contain alpha-numeric characters and underscore Example:
$VAL, $_value2

4. Variable names cannot start with number


Example: $VAL, $_value2
5. Separate variable names by using underscores
Example: $employee_details
6. Variable names is case sensitive
Example: $A not equal to $a
7. Values can assigned using = operator
Example: $A = 0;
8. Special Keyword can be use as variable name
Example: $return = 0;

Variables
A variable is a "container" for storing information. Variable can have a short name
(eg: x) or more descriptive name (eg: age).
Declaring PHP variables

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

22

Rules for PHP variables:

Variable start with the dollar($) sign, followed by the name of the variable

Variable name start with a letter or the underscore(_) character

Variable name declared cannot start with a number

Variable name can only consist of alpha-numeric characters and underscores (A-z, 0-9,
and _ )

Variable name are case-sensitive ($ACE and $ace are two different variables)
Example:
<?php
$txt = "Hello world!";
$x = 5;
$_y = 10.5;
?>

Assign value to PHP variables


PHP variables can hold several different data types as variable value. Single equal sign(=)
is used to store information in variables.
Example:
$age = 20;
$price = 2.85;
$number = -1;
$name = "Little Brothers";

Remove value from PHP variables and uncreate PHP variables


To clear out the value from the PHP variables.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

23

Example: $age = "";


To uncreate the PHP variables.
Example: unset($age);

Binding
LATE STATIC BINDING
With the introduce of PHP 5.3, late static binding was introduced. Late static binding can
be used to reference the called class in context static inheritance. Late static binding work by
storing the class named in the last non-forwarding call. In static method call, this is the class
explicitly named. In non-static method call, it is the class of the object. A forwarding call is a
static one that introduced by self::,parent::, and static::. Late static binding is trying to solve the
limitation of self:: by using static keyword that was already reserved to references the class that
initially called at runtime.
Example: Static Context
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

24

public static function who() {


echo __CLASS__;
}
}
B::test();
?>

Example: Non-static context


<?php
class A {
private function foo() {
echo "success!\n";
}
public function test() {
$this->foo();
static::foo();
}
}
class B extends A {
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
class C extends A {
private function foo() {
/* original method is replaced; the scope of the new one is C */
}

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

25

}
$b = new B();
$b->test();
$c = new C();
$c->test(); //fails
?>

Since $this-> will calling private method from the same scope, using static:: may giving a
different result ans static:: can only refer to static properties.
Data Type
Variables can store information of different types, and different data types can do
different things.
PHP supported data types:

String

Integer

Float (floating point numbers - also called double)

Boolean

Array

Object

NULL

Resource

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

26

PHP String
A string data type is a sequence of characters, like "Hello guys". A string can be any text put
between the quotes. You can use single or double quotes:
Example:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
An integer is a whole number (without decimals). It can be a number between
-2,147,433,658 and +2,147,423,617.
Rules for integers:

Must have at least one digit (0-9)

Cannot contain comma or blanks

Must not have a decimal point

Can be either positive or negative

Can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed


with 0x) or octal (8-based - prefixed with 0)

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

27

Example
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float data type (floating point number) is a number with a decimal point or a number in
exponential form.
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean will only represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
PHP Array
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:

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

28

Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Object
Object is a data type which stores data and information on how to process that data. In PHP,
object must be explicitly declared. To declare a class of object, we use the class keyword. A class
can contain properties and methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
}
}

// create an object
$herbie = new Car();

// show object properties

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

29

echo $herbie->model;
?>
PHP NULL Value
Null is a special data type which can only one value: NULL. A variable with NULL data type is a
variable that has no value assigned to it.
Example
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It holding a reference to external resource.
The resources are created and used by special functions.
Example:
<?php
// prints: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// prints: stream

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

30

$fp = fopen("foo", "w");


echo get_resource_type($fp) . "\n";

// prints: domxml document


$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";
?>

Scope
Scope of a variable is the context within which variable is defined. Most part of all PHP
variables only have a single scope. Single scope spans included and required files as well.
Local variable
Example:
<?php
$a = 1;
include 'b.inc';
?>

Here the $a variable only available within the included b.inc script. However, the user-defined
functions a local function scope is introduced. All variable used inside a function will be default
limited to the local function scope. For example:
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

31

The above script will not produce any output because the echo statement refers to a local version
of the $a variable, and it has not been assigned a value within this scope. In PHP global variables
must be declared global inside a function if they going to be used in the function.

Global variable
Example:
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
The above script will produce an output of 3. By declaring $a and $b as global within function,
all references to the variable will refer to global version.
Static variable
Static variable exists in local function scope, but it do not lose value when program leaves this
scope.
<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>

$a is initialized in first call if function and when test() function called every time, it will print out
the value of $a and increase the value by 1.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

32

Lifetime of a variables or objects


In PHP, a variable will live until the whole page has finished being parsed. If you like to destroy
the $variable, you have to call the function unset() or unset($variable);
In PHP, the variables in the contents of $_SESSION are retained which means that whenever a
script executes objects and variables are created and upon completion all objects/variables are
destroyed.
For Functions in PHP, there have their own private name space which mean the variables used
within those functions are locally scoped only to that function and are ignorant of any variables
of the same name outside of that function.
Referencing Environment
The referencing environment of a statement is the collection of all names that are visible in the
statement
Local Variables
Variable declared in a function is considered local. It can be referenced solely in that function.
Assignment outside of that function will be considered as a different variable from the one
contained in the function
Example
<?php
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. <br />";
}

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

33

assignx();
print "\$x outside of function is $x. <br />";
?>
OUTPUT:
$x inside function is 0.
$x outside of function is 4.

Global Variables - Superglobals


The PHP common superglobal variables are:

$GLOBALS

$_REQUEST

$_POST

$_GET

PHP $GLOBALS
Used to access the global variables from anywhere in the PHP script.
Example
<?php
$x = 75;
$y = 25;
function addition() {

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

34

$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];


}
addition();
echo $z;
?>

In the above script, $z is a global variable so it is accessible from outside the function.

PHP $_REQUEST

Used to collect data after submitting an HTML form.


Example:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

35

PHP $_POST

Widely used to collect form data after submitting an HTML form with method="post" and used
to pass variables as well.
Example:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>

PHP $_GET
Used to collect form data after submitting an HTML form with method="get".
We have an HTML page that contains a hyperlink with parameters:
<html>
<body>
<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

36

</body>
</html>

User clicks on the link "Test $GET", the parameters "subject" and "web" is sent to
"test_get.php", and to access the values in "test_get.php" we need to use $_GET.
Example:
<html>
<body>
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
</body>
</html>

OUTPUT:
Study PHP at W3schools.com

Support Programming Style


Object-oriented programming
Documentation is organized using the object-oriented interface. The object-oriented
interface shows functions grouped by their purpose, making it easier to get started. The reference
section gives examples for both syntax variants.
Example
<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
if (mysqli_connect_errno($mysqli)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$res = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

37

$row = mysqli_fetch_assoc($res);
echo $row['_msg'];

$mysqli = new mysqli("example.com", "user", "password", "database");


if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}

$res = $mysqli>query("SELECT 'choices to please everybody.' AS _msg FROM DUAL)


;
$row = $res->fetch_assoc();
echo $row['_msg'];
?>

OUTPUT:
A world full of choices to please everybody.

Imperative programming
The imperative interface is same with the old mysql extension. The function names differ
only by prefix. Some mysql functions take a connection handle as the first argument, whereas
matching functions with the old mysql interface take it as an optional last argument.
Example
<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$res = mysqli_query($mysqli, "SELECT 'Please, do not use ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($res);

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

38

echo $row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");


mysql_select_db("test");
$res = mysql_query("SELECT 'the mysql extension for new developments.' AS _msg
FROM DUAL", $mysql);
$row = mysql_fetch_assoc($res);
echo $row['_msg'];
?>

OUTPUT:

Please, do not use the mysql extension for new developments.

Distinct features of PHP


1. No need to specify data type for variable declaration. It can be determined at the time of
execution depends on the value of the variable.
2. Provides cross platform compatibility, unlike other server side scripting language.
3. Has set of pre-defined variables called superglobals which start by _. For examples,
$_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER and etc.
4. The name of the variable can be change dynamically.
5. Contains access monitoring capability to create logs as the summary of recent accesses.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

39

6. Includes several magic methods that begins with __ character which will be defined and
called at appropriate instance. Example, __clone().
7. Supports extended regular expression that leads extensive pattern matching with
remarkable speed.
8. Since PHP is a single inheritance language, parent class methods can be derived by only
one directly inherited sub class. But the implementation of the traits concept, reduce the
gap over this limitation and allow to reuse required method in several classes.

Application Domain of PHP

PHP is a server-side scripting language designed for web development and also used as
a general-purpose

programming

language. PHP

language

can

also

simply

mixed

with HTML code and can used in combination with various templating engines and web
frameworks. PHP is usually processed by PHP interpreter, which usually implemented as a web
server's native module or Common Gateway Interface (CGI) executable. After that the PHP code
is interpreted and executed, the web server sends the output to the client, usually in the form of a
part of the generated web page; example, PHP can generate a web page's HTML code, an image,
or some other data. PHP has also evolved to include a command-line interface (CLI) capability
and can be used in standalone graphical applications.
PHP applications are geared toward functions that involve database access, such as search
engines, e-commerce and advertising but now they also can be used for inter-browser
communications and games. Social media sites, electronic forums and remote access for
businesses and educational institutions are also the examples of where PHP applications are
regularly deployed.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

40

PHP can be used on major operating systems, including Linux, many Unix variants
(including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and so
on. Besides that, PHP also support most of the web servers today which includes Apache, IIS.
And this also includes any web server that can utilize the FastCGI PHP binary, like lighttpd and
nginx. PHP works as either a module, or as a CGI processor.

Current Status of PHP

In my point of view, PHP is still a popular programming language. According to TIOBE


website, PHP is currently allocated at the top 7 of the TIOBE chart. To anyone who visited the
Facebook, Wikipedia or any WordPress-powered blogs, you are experienced PHP in action. The
web page and the file ends in the extension .php rather than .html, the page you are viewing will
run through pre-processor before served to your browser. Its not just a common social website
but blogs that heavily on PHP programming.
There are several reasons why PHP is so popular recently. One of the reason is PHP is a
server-side script rather than client side which mean the processing is done on the Web hosts
server, rather than on your machine. So the users can access to the sites such as Facebook from
any computer by entering the username and password to login into their account.
Besides that, PHP is an Open Source which everyone can access and edit the source code
and contribute the future development. This also one of the reason why so many plug-in
programs available written in PHP. Because PHP is an Open Source, so there are no licensing
fees to pay to install it which will decrease the cost of running a server.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

41

Other than that, PHP is a platform independent and even runs on a Window server which
mean it is a pre-installed by the majority of web hosting companies on their server which
complete with library script to install on your domain. Finally, PHP is a easy to learn
programming language which mean users can start off with a standard installation of program
and tweak it to meet own specific need.

CONCLUSION REMARKS
Comparison of both languages
From all the works we have done, we conclude that although PHP and C++ programming
languages share the similar syntax and function definitions but they are two different languages
that are served on different purposes. PHP are used for design websites that interact with
databases while C++ creates stand-alone applications. Besides that, C++ is a compiled
language that in the compilation progress C++ codes needs to be compiled into binary then
becoming an .exe but PHP as a interpreted language can be interpreted directly from the source
by Apache. Furthermore, the biggest differences is PHP has no variable types and C++ is
strongly typed. Which mean every variables in C++ must have a known type at compile time; but
not in PHP that only use a dollar sign($) and have no declared type. More often, PHP has
interfaces and does not allow multiple inheritance while C++ react on the opposite way on the
object system.
Opinions
In our opinion, PHP is a simple program language. For all the users, PHP is easy to learn,
easy to write, easy to read, libraries available and easy to debug. Besides that, because PHP is a
scripting language, it has major benefits in terms of programmer productivity and the ability to

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

42

iterate quickly on products but scripting languages are known to generally be less efficient when
it comes to CPU and memory usages.Language which are interpreted are much more slower
compare to the compiled languages. This is one of reason why Facebook compiles PHP to C++.

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

43

References for C++

1. Alex Allain. Lambda Functions in C++ 11 the Definitive Guide. Retrieved August
2.
3.
4.
5.

29,2015 from http://www.cprogramming.com/c++11/c++11-lambda-closures.html


http://oss.org.cn/ossdocs/gnu/c++-tutorial/tutorial/tut3-6.html
http://www.mathcs.emory.edu/~cheung/Courses/561/Syllabus/3-C/scoping.html
http://www.studytonight.com/cpp/variables-scope-details.php
Alex.(2008, Feb 7).12.4 Early binding and late binding Retrieved August 29,2015 from

http://www.learncpp.com/cpp-tutorial/124-early-binding-and-late-binding/
6. http://www.tutorialspoint.com/cplusplus/cpp_variable_types.htm
7. Brian McNamara.(2003, Aug 22).LC ++ Logic Programming in C++. Retrieved August
29,2015 from http://yanniss.github.io/lc++/
8. http://bytes.com/topic/c/answers/494248-c-shines-what-application-domains
9. http://stackoverflow.com/questions/537595/which-sector-of-software-industry-uses-c
10. http://www.c4learn.com/cplusplus/cpp-variable-naming/
11. https://en.wikipedia.org/wiki/The_C%2B%2B_Programming_Language
12. Albatross.History of C++. Retrieved August 29,2015 from
http://www.cplusplus.com/info/history/
13. http://www.codingunit.com/cplusplus-tutorial-history-of-the-cplusplus-language
14. Navarre Ginsberg.(Apr 30),C++(programming language): What are the features of C++
which most programmers dont know? Retrieved August 29,2015 from
http://www.quora.com/C++-programming-language/What-are-the-features-of-C++which-most-programmers-dont-know
15. Jim Dennis.(Jun 20).What is the best features that is unique to that programming
language? Retrieved August 29,2015 from http://www.quora.com/What-is-the-bestfeature-that-is-unique-to-that-programming-language
16. Arne Mertz.(2015, July 19). New C++ Features std::begin / end and range based for
loops Retrieved August 29,2015 from http://arne-mertz.de/2015/07/new-c-featuresstdbeginend-and-range-based-for-loops/
17. Bartosz Milewski(Aug 23).SafeD Retrieved August 29,2015 from
http://dlang.org/safed.html
18. http://www.boost.org/

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

44

19. http://www.equestionanswers.com/cpp-questions.php
20. http://www.programmingsimplified.com/c-program-examples
21. Mathieu Dutour Siiric.(mar 14).Is C++ is a functional programming language or not?
Retrieved August 29,2015 from http://www.quora.com/Is-C++-is-a-functionalprogramming-language-or-not
22. http://voices.canonical.com/jussi.pakkanen/2013/10/15/c-has-become-a-scriptinglanguage/
23. http://www.infoworld.com/article/2947536/application-development/javascript-rules-theschool-but-c-climbs-in-popularity.html
24. http://stackoverflow.com/questions/1549990/in-which-area-is-c-mostly-used
25. http://www.cplusplus.com/forum/general/16038
26. http://www.quora.com/Is-Java-the-most-commonly-used-language-in-the-softwareindustry
27. http://www.stroustrup.com/applications.html
28. http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
29. http://blog.learntoprogram.tv/%E2%80%8Btop-seven-programming-languages-to-learnfor-2018/
30. http://www.quora.com/Is-C++-still-so-much-faster-that-it-actually-matters-to-use-itwhen-programming-games
31. http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
32. https://www.quora.com/What-is-the-difference-between-PHP-and-C++

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

45

References for PHP


1. http://www.w3schools.com/php/php_superglobals.asp
2. Kingfeanor.(2010, March 31).Whats better C++ or PHP? Retrieved August 29,2015 from
http://www.dreamincode.net/forums/topic/165308-whats-better-c-or-php/
3. Kawsar Ahmad.( 2013, Feb 15).What is the difference between PHP and C++?. Retrieved
August 29,2015 from https://www.quora.com/What-is-the-difference-between-PHP-andC++
4. Von Vincent Tscherter.(2015, Feb 16).EBNF Parser & Syntax Diagram Renderer.
Retrieved August 29,2015 from http://karmin.ch/ebnf/index
5. http://www.tutorialspoint.com/php/php_local_variables.htm
6. Marc Plotz.(2015).Principles of Object Oriented Programming in PHP. Retrieved August
29,2015 from http://www.htmlgoodies.com/beyond/php/article.php/3909681
7. http://php.net/manual/en/mysqli.quickstart.dual-interface.php
8. Eugene P.(2015, August 01).What are the different Types of PHP Applications?.
Retrieved August 29,2015 from http://www.wisegeek.net/what-are-the-different-types-ofphp-applications.htm
9. https://en.wikipedia.org/wiki/PHP#Implementations
10. http://docstore.mik.ua/orelly/webprog/php/ch03_03.htm
11. Compnerd814.(2008).PHP variable lifetime (confusing). Retrieved August 29,2015 from
https://answers.yahoo.com/question/index?qid=20080706224225AA7hEFK
12. Angela Bradley.What is PHP Used For?. Retrieved August 29,2015 from
http://php.about.com/od/phpbasics/qt/what_is_php_used_for.htm
13. Vincy.(2013, April 14).Unique Features of PHP. Retrieved August 29,2015 from
http://phppot.com/php/unique-features-of-php/
14. http://scholar.lib.vt.edu/manuals/php3.0.6/intro-history.html
15. http://php.net/manual/en/language.variables.scope.php
16. http://php.net/manual/en/language.oop5.late-static-bindings.php
17. Neerav Mehta.(2015, Aug 18).Object Oriented PHP. Retrieved August 29,2015 from
http://redcrackle.com/blog/drupal-8/object-oriented-php
18. Gail Seymour.Why Is PHP so Popular. Retrieved August 29,2015 from
http://www.hostway.com/web-resources/how-to-build-a-website/website-code/why-isphp-so-popular/

TPL2141 - PROGRAMMING LANGUAGE CONCEPT

Appendix
EBNF Syntax of C++
Name

Production

abstract_declarator

ptr_operator [ abstract_declarator ]

direct_abstract_declarator

'private'

'protected'

'public'

access_specifier

46

TPL2141 - PROGRAMMING LANGUAGE CONCEPT


Name

47

Production

additive_expression

multiplicative_expression

additive_expression '+' multiplicative_expression

additive_expression '-' multiplicative_expression

equality_expression

and_expression '&' equality_expression

conditional_expression

logical_or_expression assignment_operator assignment_expressio


n

throw_expression

'='

'*='

'/='

'%='

'+='

'-='

'>>='

'<<='

'&='

'^='

and_expression

assignment_expressi
on

assignment_operator

TPL2141 - PROGRAMMING LANGUAGE CONCEPT


More

can

be

found

in

here

http://www.externsoft.ch/download/cpp-

iso.html#unary_expression

EBNF Syntax of PHP


<ebnf> "EBNF defined in itself" {
syntax

= [ title ] "{" { production } "}" [ comment ].

production = identifier "=" expression ( "." | ";" ) .


expression = term { "|" term } .
term

= factor { factor } .

factor

= identifier
| literal
| "[" expression "]"
| "(" expression ")"
| "{" expression "}" .

identifier = character { character } .


title

= literal .

comment
literal

= literal .

= "'" character { character } "'"


| '"' character { character } '"' .

}</ebnf>

48

TPL2141 - PROGRAMMING LANGUAGE CONCEPT


More can be found in here : http://karmin.ch/ebnf/index

49

También podría gustarte