Update Terbaru
Loading...

Artikel Blog

Wednesday 18 December 2013
no image

PHP Basics

In this part of the PHP tutorial, we will talk about basic programming in PHP.
All the PHP code is surrounded by two delimiters, <?php and ?>. The 'php' string is optional but recommended.
<?php 

# PHP code

?>
PHP code is put between two delimiters.
<?php 

$a = 23;
print $a;

?>
This PHP script assigns a value to a variable. It prints it to the console. Note that we say console, because here we use the PHP_CLI command line interpreter. If you test these examples on the web, the output will be sent to the browser.
$a = 23;
We assign a value 23 to the $a variable. Each variable starts with a dollar character. This PHP code line is a statement. Each statement ends with a semicolon. In PHP, semicolons are not mandatory, like in Javascript or Ruby. They are obligatory.
print $a;
We print the $a variable to the console. The print keyword does not add a new line to the output. If we want a new line, we must put it manually. print keyword takes only one argument.
<?php 

$a = 23;
$b = 24;

echo $a, "\n", $b, "\n";

?>
In this script, we use the echo keyword. It is similar to the print keyword. Unlike the print keyword, it can take multiple arguments.
$a = 23;
$b = 24;
We define two variables.
echo $a, "\n", $b, "\n";
We print the variables to the console. We also include the new line characters. Arguments can be separated by commas.
$ php echo.php 
23
24
This is the output of the script.

Types

PHP is a weakly typed language. It works with types, but the programmer does not specify them when declaring variables. A data type is a one of various types of data, as double, integer, or boolean. Values of a certain data type are from a specific range of values stating the possible values for that type, the operations that can be done on that type, and the way the values of that type are stored. PHP works implicitly with data types. Programmers do not specify explicitly the data types.
<?php 

$a = "Jane";
echo "$a \n";

$a = 12;
echo "$a \n";

$a = 56.4;
echo "$a \n";

$a = true;
echo "$a \n";

?>
In this PHP script, we have an $a variable. First, we assign it a string, then an integer, a double and finally a boolean value. If we assign a string to a variable the PHP automatically creates a string variable.
$ php dynamic.php 
Jane 
12 
56.4 
1 
Running the script.
<?php 

$temperature = 12.4;
$name = "Jane";
$age = 17;
$values = array(1, 2, 3, 4, 5, 6); 

class Being {};

$somebody = new Being();

echo gettype($temperature), "\n";
echo gettype($name), "\n";
echo gettype($age), "\n";
echo gettype($values), "\n";
echo gettype($somebody), "\n";

?>
In the above PHP script, we dynamically create five types.
$values = array(1, 2, 3, 4, 5, 6); 

class Being {};
This is an array and a class. Both types will be covered later in more detail.
echo gettype($temperature), "\n";
The gettype() function returns the type of the variable in question.
$ php gettype.php 
double
string
integer
array
object
This script lists the basic types of the PHP language.

Constants

In PHP, we can create constants. A constant is a name for a value that, unlike a variable, cannot be reassociated with a different value. We use the define() function to create constants in PHP.
<?php 

define("BLUE", "0000FF");

echo BLUE, "\n";

echo defined("BLUE");
echo "\n";

?>
In this PHP script, we define a BLUE constant.
define("BLUE", "0000FF");
Here we define the BLUE constant. It is a convention to write constants in uppercase letters.
echo BLUE, "\n";
Here we use it. Note that constants are not preceded by ($) dollar character.
echo defined("BLUE");
We have used another function, the defined() function. It checks, if a particular constant exists. Returns true, if it does.
$ php constant.php 
0000FF
1
Running the example gives the above output.
PHP also has some predefined constants.
<?php 

echo TRUE;
echo "\n";
echo PHP_VERSION;
echo "\n";
echo PHP_OS;
echo "\n";
echo __LINE__;
echo "\n";
echo __FILE__;
echo "\n";
echo DIRECTORY_SEPARATOR;
echo "\n";
echo PHP_DATADIR;
echo "\n";

?>
Here we print some built-in PHP constants. For example, the PHP_OS constant prints the OS version on which the PHP was built.
$ php constants.php 
1
5.2.6-2ubuntu4.6
Linux
9
/home/vronskij/programming/php/basics/constants.php
/
${prefix}/share
On my system, I get this output.

Variable interpolation

Next, we will define interpolation. Variable interpolation is replacing variables with their values inside string literals. Another names for variable interpolation are: variable substitution and variable expansion.
<?php 

$age = 17;

echo "Jane is $age years old\n";

?>
The $age variable is replaced with the value 17 in the string.
$ php interpolation.php 
Jane is 17 years old
<?php 

$age = 17;

echo 'Jane is $age years old\n';

?>
However, this does not work, if we use the single quotes. In this case, no interpolation happens and no special characters are working.
$ php interpolation2.php 
Jane is $age years old\n$ 
We see a verbatim output of the string.

Including files

PHP code is split in multiple files for bigger programs. We use the include statement to join various PHP files.
<?php 

define("VERSION", 1.12);

function get_max($x, $y) {
    if ($x > $y) {
        return $x;
    } else {
        return $y;
    }
}

?>
Let's say, we have a common.php file, in which we define some constants and functions.
<?php 

include "common.php";

echo "The version is " . VERSION . "\n";

$a = 5;
$b = 3;

echo get_max($a, $b), "\n";

?>
And we have another file, which wants to use the aforementioned definitions.
include "common.php";
We simply include the definitions to our file with the include keyword. We must specify the exact path to the common.php file. In our simple case, both files are in the same directory.
This chapter covered some basics of the PHP language.
no image

Object-oriented programming in Visual Basic 6.0

There are three widely used programming paradigms there. Procedural programming, functional programming and object-oriented programming. Visual Basic supports both procedural and object-oriented programming.
Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. (Wikipedia)
There are some basic programming concepts in OOP:
  • Abstraction
  • Polymorphism
  • Encapsulation
  • Inheritance
The abstraction is simplifying complex reality by modeling classes appropriate to the problem. The polymorphism is the process of using an operator or function in different ways for different data input. The encapsulation hides the implementation details of a class from other objects. The inheritance is a way to form new classes using classes that have already been defined.

Objects

Objects are basic building blocks of a Visual Basic OOP program. An object is a combination of data and methods. In a OOP program, we create objects. These objects communicate together through methods. Each object can receive messages, send messages and process data.
There are two steps in creating an object. First, we create a class. A class is a template for an object. It is a blueprint, which describes the state and behavior that the objects of the class all share. A class can be used to create many objects. Objects created at runtime from a class are called instances of that particular class.
Option Strict On


Module Example

    Class Being
    
    End Class

    Sub Main()
        
        Dim b as New Being
        Console.WriteLine(b.ToString())      

    End Sub
    
End Module
In our first example, we create a simple object.
Class Being

End Class
This is a simple class definition. The body of the template is empty. It does not have any data or methods.
Dim b as New Being
We create a new instance of the Being class. For this we have the New keyword. The b variable is the handle to the created object.
Console.WriteLine(b.ToString())
The ToString() method of the object gives some basic description of the object.
$ ./object.exe 
Example+Being
We don't get much info, since the class definition was empty. We get the object class name and the module name, where the instance of this object was created.

Object attributes

Object attributes is the data bundled in an instance of a class. The object attributes are called instance variables or member fields. An instance variable is a variable defined in a class, for which each object in the class has a separate copy.
Option Strict On


Module Example

    Class Person

        Public Name As String
    
    End Class

    Sub Main()
        
        Dim p1 as New Person
        p1.Name = "Jane"

        Dim p2 as New Person
        p2.Name = "Beky"

        Console.WriteLine(p1.Name)
        Console.WriteLine(p2.Name)      

    End Sub
    
End Module
In the above Visual Basic code, we have a Person class with one member field.
Class Person
    Public Name As String
End Class
We declare a Name member field. The Public keyword specifies, that the member field will be accessible outside the Class/End Class block.
Dim p1 as New Person
p1.Name = "Jane"
We create an instance of the Person class. And set the Name variable to "Jane". We use the dot operator to access the attributes of objects.
Dim p2 as New Person
p2.Name = "Beky"
We create another instance of the Person class. Here we set the variable to "Beky".
Console.WriteLine(p1.Name)
Console.WriteLine(p2.Name)
We print the contents of the variables to the console.
$ ./person.exe 
Jane
Beky
We see the output of the program. Each instance of the Person class has a separate copy of the Name member field.

Methods

Methods are functions/procedures defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are essential in encapsulation concept of the OOP paradigm. For example, we might have a Connect method in our AccessDatabase class. We need not to be informed, how exactly the method Connect connects to the database. We only know, that it is used to connect to a database. This is essential in dividing responsibilities in programming. Especially in large applications.
Option Strict On


Module Example

    Class Circle

        Public Radius As Integer

        Public Sub SetRadius(ByVal Radius As Integer)
            Me.Radius = Radius
        End Sub

        Public Function Area() As Double
            Return Me.Radius * Me.Radius * Math.PI
        End Function
    
    End Class

    Sub Main()
        
        Dim c As New Circle
        c.SetRadius(5)

        Console.WriteLine(c.Area())

    End Sub
    
End Module
In the code example, we have a Circle class. We define two methods.
Public Radius As Integer
We have one member field. It is the Radius of the circle. The Public keyword is an access specifier. It tells that the variable is fully accessible from the outside world.
Public Sub SetRadius(ByVal Radius As Integer)
    Me.Radius = Radius
End Sub
This is the SetRadius() method. It is a normal Visual Basic procedure. The Me variable is a special variable, which we use to access the member fields from methods.
Public Function Area() As Double
    Return Me.Radius * Me.Radius * Math.PI
End Function
The Area() method returns the area of a circle. The Math.PI is a built-in constant.
$ ./circle.exe 
78.5398163397448
Running the example.

Access modifiers

Access modifiers set the visibility of methods and member fields. Visual Basic has five access modifiers. Public, Protected, Private, Friend and ProtectedFriend. Public members can be accessed from anywhere. Protected members can be accessed only within the class itself and by inherited and parent classes. Friend members may be accessed from within the same assembly (exe or dll). ProtectedFriend is a union of protected and friend modifiers.
Access modifiers protect data against accidental modifications. They make the programs more robust.
Option Strict On


Module Example

    Class Person

        Public Name As String
        Private Age As Byte

        Public Function GetAge() As Byte
            Return Me.Age
        End Function

        Public Sub SetAge(ByVal Age As Byte)
            Me.Age = Age
        End Sub
    
    End Class

    Sub Main()
        
        Dim p as New Person
        p.Name = "Jane"

        p.setAge(17)

        Console.WriteLine("{0} is {1} years old", _
           p.Name, p.GetAge)

    End Sub
    
End Module
In the above program, we have two member fields. One is declared Public, the other Private.
Public Function GetAge() As Byte
    Return Me.Age
End Function
If a member field is Private, the only way to access it is via methods. If we want to modify an attribute outside the class, the method must be declared Public. This is an important aspect of data protection.
Public Sub SetAge(ByVal Age As Byte)
    Me.Age = Age
End Sub
The SetAge() method enables us to change the Private Age variable from outside of the class definition.
Dim p as New Person
p.Name = "Jane"
We create a new instance of the Person class. Because the Name attribute is Public, we can access it directly. However, this is not recommended.
p.setAge(17)
The SetAge() method modifies the Age member field. It cannot be accessed or modified directly, because it is declared Private.
Console.WriteLine("{0} is {1} years old", _
    p.Name, p.GetAge)
Finally, we access both members to build a string.
$ ./modifiers.exe 
Jane is 17 years old
Running the example.

Option Strict On


Module Example

    Class Base

        Public Name As String = "Base"
        Protected Id As Integer = 5323
        Private IsDefined As Boolean = True
    
    End Class

    Class Derived 
        Inherits Base
    
        Public Sub Info()
            Console.WriteLine("This is Derived Class")
            Console.WriteLine("Members inherited:")
            Console.WriteLine(Me.Name)
            Console.WriteLine(Me.Id)
            'Console.WriteLine(Me.IsDefined)
        End Sub

    End Class

    Sub Main()
        
        Dim drv As Derived = New Derived
        drv.Info()
     
    End Sub
    
End Module
In the preceding program, we have a Derived class, which inherits from the Base class. The Base class has three member fields. All with different access modifiers. The IsDefined member is not inherited. The Private modifier prevents this.
Class Derived 
    Inherits Base
The class Derived inherits from the Base class.
Console.WriteLine(Me.Name)
Console.WriteLine(Me.Id)
'Console.WriteLine(Me.IsDefined)
The Public and the Protected members are inherited by the Derived class. They can be accessed. The Private member is not inherited. The line accessing the member field is commented. If we uncommented the line, it would not compile.
$ ./protected.exe 
This is Derived Class
Members inherited:
Base
5323
Running the program, we receive this output. The Public and Protected members are inherited, the Private member is not.

Method overloading

Method overloading allows the creation of several methods with the same name which differ from each other in the type of the input.
What is method overloading good for? The Qt4 library gives a nice example for the usage. The QPainter class has three methods to draw a rectangle. Their name is drawRect() and their parameters differ. One takes a reference to a floating point rectangle object, another takes a reference to an integer rectangle object and the last one takes four parameters, x, y, width, height. If the C++ language, which is the language in which Qt is developed, didn't have method overloading, the creators of the library would have to name the methods like drawRectRectF(), drawRectRect(), drawRectXYWH(). The solution with method overloading is more elegant.
Option Strict On


Module Example

    Class Sum

        Public Function GetSum() As Integer
            Return 0
        End Function

        Public Function GetSum(ByVal x As Integer) As Integer
            Return x
        End Function

        Public Function GetSum(ByVal x As Integer, _
            ByVal y As Integer) As Integer
            Return x + y
        End Function
    
    End Class

    Sub Main()
        
        Dim s As Sum = New Sum
        
        Console.WriteLine(s.getSum())
        Console.WriteLine(s.getSum(20))
        Console.WriteLine(s.getSum(20, 30))

    End Sub
    
End Module
We have three methods called GetSum(). They differ in input parameters.
Public Function GetSum(ByVal x As Integer) As Integer
    Return x
End Function
This one takes one parameter.
Console.WriteLine(s.getSum())
Console.WriteLine(s.getSum(20))
Console.WriteLine(s.getSum(20, 30))
We call all three methods.
$ ./overloading.exe 
0
20
50
And this is what we get, when we run the example.

The constructor

A constructor is a special kind of a method. It is automatically called, when the object is created. The purpose of the constructor is to initiate the state of the object. The name of the constructor in Visual Basic is New. The constructors are methods, so they can be overloaded too.
Option Strict On


Module Example

    Class Being
    
        Sub New()
            Console.WriteLine("Being is being created")
        End Sub
        
        Sub New(ByVal name As String)
            Console.WriteLine("Being {0} is created", name)
        End Sub
    
    End Class
    
    Sub Main()
        
        Dim b As New Being
        Dim t As New Being("Tom")
                
    End Sub
    
End Module
We have a Being class. This class has two constructors. The first one does not take parameters, the second one takes one parameter.
Sub New(ByVal name As String)
    Console.WriteLine("Being {0} is created", name)
End Sub
This constructor takes one String parameter.
Dim b As New Being
An instance of the Being class is created. This time the constructor without a parameter is called upon object creation.
$ ./constructor.exe 
Being is being created
Being Tom is created
This is the output of the program.

In the next example, we initiate data members of the class. Initiation of variables is a typical job for constructors.
Option Strict On


Module Example

    Class MyFriend
    
        Private Born As Date
        Private Name As String
        
        Sub New(ByVal Name As String, ByVal Born As Date)
            Me.Name = Name
            Me.Born = Born
        End Sub

        Public Sub GetInfo()
            Console.WriteLine("{0} was born on {1}", _
                Me.Name, Me.Born.ToShortDateString)
        End Sub
    
    End Class
    
    Sub Main()
    
        Dim name As String = "Lenka"    
        Dim born As Date = #5/3/1990#
    
        Dim fr As MyFriend = New MyFriend(name, born)
        fr.GetInfo()
        
    End Sub
    
End Module
We have a Friend class with data members and methods.
Private Born As Date
Private Name As String
We have two variables in the class definition. The Private keyword is an access modifier. It is a form of encapsulation. The Private keyword is the most restrictive modifier. It allows only the object in question to access the variable. No descendants, no other objects.
Sub New(ByVal Name As String, ByVal Born As Date)
    Me.Name = Name
    Me.Born = Born
End Sub
In the constructor, we initiate the two data members. The Me variable is a handler used to reference the object variables.
Dim fr As MyFriend = New MyFriend(name, born)
fr.GetInfo()
We create a Friend object with two arguments. Then we call the GetInfo() method of the object.
./constructor2.exe 
Lenka was born on 5/3/1990

Class constants

Visual Basic enables to create class constants. These constants do not belong to a concrete object. They belong to the class. By convention, constants are written in uppercase letters.
Option Strict On


Module Example

    Class Math

        Public Const PI As Double = 3.14159265359
    
    End Class

    Sub Main()
         Console.WriteLine(Math.PI)    
    End Sub
    
End Module
We have a Math class with a PI constant.
Public Const PI As Double = 3.14159265359
The Const keyword is used to define a constant.
$ ./classconstant.exe 
3.14159265359
Running the example.

The ToString() method

Each object has a ToString() method. It returns a human-readable representation of the object. The default implementation returns the fully qualified name of the type of the Object. Note that when we call the Console.WriteLine() method with an object as a parameter, the ToString() is being called.
Option Strict On


Module Example

    Class Being
    
        Public Overrides Function ToString As String    
            Return "This is Being Class"
        End Function
    
    End Class

    Sub Main()
        
        Dim b as New Being
        Dim o As New Object

        Console.WriteLine(o.ToString())
        Console.WriteLine(b.ToString())     
        Console.WriteLine(b) 

    End Sub
    
End Module
We have a Being class in which we override the default implementation of the ToString() method.
Public Overrides Function ToString As String    
    Return "This is Being Class"
End Function
Each class created inherits from the base Object. The ToString() method belongs to this Object class. We use the Overrides keyword to inform, that we are overriding a method.
Dim b as New Being
Dim o As New Object
We create two objects. One custom defined and one built-in.
Console.WriteLine(o.ToString())
Console.WriteLine(b.ToString())  
We call the ToString() method on these two objects.
Console.WriteLine(b) 
As we have specified earlier, calling the Console.WriteLine() on the object will call its ToString() method.
$ ./override.exe 
System.Object
This is Being Class
This is Being Class
This is what we get, when we run the script.

Inheritance

The inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).
Option Strict On


Module Example

    Class Being
        Sub New()
            Console.WriteLine("Being is created")
        End Sub
    End Class
    
    Class Human 
        Inherits Being
    
        Sub New()
            Console.WriteLine("Human is created")
        End Sub
    
    End Class
    
    Sub Main()
        
        Dim h As New Human
        
    End Sub
    
End Module
In this program, we have two classes. A base Being class and a derived Human class. The derived class inherits from the base class.
Class Human 
    Inherits Being
In Visual Basic, we use the Inherits keyword to create inheritance relations.
Dim h As New Human
We instantiate the derived Human class.
$ ./inheritance.exe 
Being is created
Human is created
We can see, that both constructors were called. First, the constructor of the base class is called, then the constructor of the derived class.

A more complex example follows.
Option Strict On


Module Example

    Class Being
    
        Dim Shared Count As Integer = 0
    
        Sub New()
            Count = Count + 1
            Console.WriteLine("Being is created")
        End Sub
        
        Sub GetCount()
            Console.WriteLine("There are {0} Beings", Count)
        End Sub
        
    End Class
    
    Class Human 
        Inherits Being
    
        Sub New()
            Console.WriteLine("Human is created")
        End Sub
    
    End Class
    
    Class Animal 
        Inherits Being
        
        Sub New
            Console.WriteLine("Animal is created")
        End Sub
        
    End Class
    
    Class Dog
        Inherits Animal
        
        Sub New()
            Console.WriteLine("Dog is created")
        End Sub
        
    End Class
    

    Sub Main()
        
        Dim h As New Human
        Dim d As New Dog
        d.GetCount()
        
    End Sub
    
End Module
We have four classes. The inheritance hierarchy is more complicated. The Human and the Animal classes inherit from the Being class. And the Dog class inherits directly from the Animal class and indirectly from the Being class. We also introduce a concept of a Shared variable.
Dim Shared Count As Integer = 0
We define a Shared variable. Shared members are members, that are shared by all instances of a class. In other programming languages, they are called static members.
Sub New()
    Count = Count + 1
    Console.WriteLine("Being is created")
End Sub
Each time the Being class is instantiated, we increase the Count variable by one. This way we keep track of the number of instances created.
Class Animal 
    Inherits Being
...
Class Dog
    Inherits Animal
...
The Animal inherits from the Being and the Dog inherits from the Animal. Indirectly, the Dog inherits from the Being as well.
Dim h As New Human
Dim d As New Dog
d.GetCount
We create instances from the Human and from the Dog classes. We call the GetCount() method of the Dog object.
$ ./inheritance2.exe 
Being is created
Human is created
Being is created
Animal is created
Dog is created
There are 2 Beings
The Human object calls two constructors. The Dog object calls three constructors. There are two Beings instantiated.

Abstract classes and methods

Abstract classes cannot be instantiated. If a class contains at least one abstract method, it must be declared abstract too. Abstract methods cannot be implemented, they merely declare the methods' signatures. When we inherit from an abstract class, all abstract methods must be implemented by the derived class. Furthermore, these methods must be declared with the same of less restricted visibility.
Unlike Interfaces, abstract classes may have methods with full implementation and may also have defined member fields. So abstract classes may provide a partial implementation. Programmers often put some common functionality into abstract classes. And these abstract classes are later subclassed to provide more specific implementation. For example, the Qt graphics library has a QAbstractButton, which is the abstract base class of button widgets, providing functionality common to buttons. Buttons Q3Button, QCheckBox, QPushButton, QRadioButton, and QToolButton inherit from this base abstract class.
Formally put, abstract classes are used to enforce a protocol. A protocol is a set of operations, which all implementing objects must support.
Option Strict On


Module Example

    MustInherit Class Drawing
        Protected x As Integer = 0
        Protected y As Integer = 0

        Public MustOverride Function Area() As Double

        Public Function GetCoordinates() As String
            Return String.Format("x: {0}, y: {1}", _
                Me.x, Me.y)
        End Function
    
    End Class

    Class Circle  
        Inherits Drawing

        Private Radius As Integer

        Sub New(ByVal x As Integer, ByVal y As Integer, _
            ByVal r As Integer)
            Me.x = x
            Me.y = y
            Me.Radius = r
        End Sub 

        Public Overrides Function Area() As Double
            Return Me.Radius * Me.Radius * Math.PI
        End Function

        Public Overrides Function ToString() As String
            Return String.Format("Circle, at x: {0}, y: {1}, radius: {2}", _
                Me.x, Me.y, Me.Radius)
        End Function

    End Class

    Sub Main()
        
        Dim c as New Circle(12, 45, 22)
       
        Console.WriteLine(c)
        Console.WriteLine("Area of circle: {0}", c.Area())
        Console.WriteLine(c.GetCoordinates())

    End Sub
    
End Module

We have an abstract base Drawing class. The class defines two member fields, defines one method and declares one method. One of the methods is abstract, the other one is fully implemented. The Drawing class is abstract, because we cannot draw it. We can draw a circle, a dot or a square. The Drawing class has some common functionality to the objects, that we can draw.
MustInherit Class Drawing
In Visual Basic, we use the MustInherit keyword to define an abstract class.
Public MustOverride Function Area() As Double
An abstract method is preceded with a MustOverride keyword.
Class Circle  
    Inherits Drawing
A Circle is a subclass of the Drawing class. It must implement the abstract Area() method.
$ ./abstractclass.exe 
Circle, at x: 12, y: 45, radius: 22
Area of circle: 1520.53084433746
x: 12, y: 45
Output of the program.
This was the first part of the description of OOP in Visual Basic.
Tuesday 17 December 2013
no image

PHP lexical structure

Computer languages, like human languages, have a lexical structure. A source code of a PHP script consists of tokens. Tokens are atomic code elements. In PHP language, we have comments, variables, literals, operators, delimiters and keywords.

Comments

Comments are used by humans to clarify the source code. All comments in PHP follow the # character.
<?php

# comments.php
# author Jan Bodnar
# ZetCode 2009

echo "This is comments.php script\n";

?>
Everything that follows the # character is ignored by the PHP interpreter.
// comments.php
// author Jan Bodnar
// ZetCode 2009

/*
 comments.php
 author Jan Bodnar
 ZetCode 2009
*/
PHP also recognizes the comments from the C language.

White space

White space in PHP is used to separate tokens in PHP source file. It is used to improve readability of the source code.
public $isRunning;
White spaces are required in some places. For example between the access specifier and the variable name. In other places, it is forbidden. It cannot be present in variable identifiers.
$a=1;
$b = 2;
$c  =  3;
The amount of space put between tokens is irrelevant for the PHP interpreter.
$a = 1;
$b = 2; $c = 3;
$d 
  = 
   4;
We can put two statements into one line. Or one statement into three lines. However, source code should be readable for humans. There are accepted standards of how to lay out your source code.

Semicolon

A semicolon is used to mark the end of a statement in PHP. It is mandatory.
$a = 34;
$b = $a * 34 - 34;
echo $a;
Here we have three different PHP statements. The first is an assignment. It puts a value into the $a variable. The second one is an expression. The expression is evaluated and the output is given to the $b variable. The third one is a command. It prints the $a variable.

Variables

A variable is an identifier, which holds a value. In programming we say, that we assign a value to a variable. Technically speaking, a variable is a reference to a computer memory, where the value is stored. In PHP language, a variable can hold a string, a number or various objects like a function or a class. Variables can be assigned different values over time.
Variables in PHP consist of the $ character and a label. A label can be created from alphanumeric characters and an underscore (_) character. A variable cannot begin with a number. The PHP interpreter can then distinguish between a number and a variable more easily.
$Value
$value2
$company_name
These were valid identifiers.
$12Val
$exx$
$first-name
These were examples of invalid identifiers.
The variables are case sensitive. This means, that $Price, $price, and $PRICE are three different identifiers.
<?php

$number = 10;
$Number = 11;
$NUMBER = 12;

echo $number, $Number, $NUMBER;

echo "\n";

?>
In our script, we assign three numeric values to three variables and print them.
101112
This is the output of the script.

A literal

A literal is any notation for representing a value within the PHP source code. Technically, a literal will be assigned a value at compile time, while a variable will be assigned at runtime.
$age = 29;
$nationality = "Hungarian";
Here we assign two literals to variables. Number 29 and string Hungarian are literals.
<?php

$name1 = "Jane ";
$age1 = 17;

$name2 = "Rose ";
$age2 = 16;

echo "Patrick 34\n";
echo "Luke 22\n";

echo $name1, $age1, "\n";
echo $name2, $age2, "\n";

?>
If we do not assign a literal to a variable, there is no way, how we can work with it. It is dropped.
$ php literals.php
Patrick 34
Luke 22
Jane 17
Rose 16
This is the output of the literals.php script.

Operators

An operator is a symbol used to perform an action on some value. (answers.com)
+    -    *    /    %    ++    --
=    +=   -=   *=   /=   .=    %=
==   !=   ><   >   <   >=   <= 
&&   ||   !   xor   or    
&    ^    |   ~   .   <<   >>   
These are PHP operators. We will talk about operators later in the tutorial.

Delimiters

A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data stream. (wikipedia)
$a = "PHP";
$b = 'Java';
The single and double characters are used to mark the beginning and the end of a string.
function setDate($date) {
    $this->date = $data;
}

if ( $a > $b) {
    echo "\$a is bigger than \$b";
}

Parentheses are used to mark the function signature. The signature is the function parameters. Curly brackets are used to mark the beginning and the end of the function body. They are also used in flow control.
$a = array(1, 2, 3);
echo $a[1];
The square brackets are used to mark the array index.
/*
 Author Jan Bodnar
 December 2009
 ZetCode
*/
/* */ delimiters are used to provide C style comments in PHP.
<?php
// PHP code
?>
The <?php and ?> delimiters are used to delimit PHP code in a file.

Keywords

A keyword is a reserved word in the PHP programming language. Keywords are used to perform a specific task in the computer program. For example, print a value, do repetitive tasks or perform logical operations. A programmer cannot use a keyword as an ordinary variable.
The following is a list of PHP keywords.
abstract    and          array()     as          break
case        catch        class       clone       const  
continue    declare      default     do          else
elseif      enddeclare   endfor      endforeach  endif
endswitch   endwhile     extends     final       for 
foreach     function     global      goto        if  
implements  interface    instanceof  namespace   new   
or          private      protected   public      static
switch      throw        try         use         var 
while       xor
The following is a list of PHP compile time constants.
__CLASS__    __DIR__       __FILE__    __FUNCTION__ 
__METHOD__   __NAMESPACE__ 
Next we have other language constructs.
die()           echo()          empty()     exit()      eval()
include()       include_once()  isset()     list()      require()
require_once()  return()        print()     unset()     
In this part of the PHP tutorial, we covered the basic lexis for the PHP language.
no image

Organizing code in visual basic 6.0

In this part of the Visual Basic tutorial, we will show, how to organize code. We will cover modules, procedures and namespaces and the scope.
Visual Basic statements are organized into blocks, modules, classes and namespaces. This helps to make the code more maintanable and robust. Correct code organization prevents from making errors in the code.
The basic building blocks of a Visual Basic program are:
  • Assembly
  • Namespace
  • Modules
  • Classes
  • Procedures and functions
  • Blocks
  • Statements
An assembly is a dll or exe file. An assembly is a compiled code library for use in deployment, versioning and security. A namespace is an abstract container providing context for the items. A module is a reference type available throughout its namespace. Classes are basic building blocks of an OOP program. A procedure is a unit of a program, that is created to do a specific task. A block is the lowest level organization of Visual Basic statements provided by some keywords like If or While. A statement is an atom in a Visual Basic program. Smallest unit of code.
Closely related to this topic is the scope and duration of a variable. A scope is the visibility of the declared variable.
ScopeDescription
Block scopeAvailable only within the code block in which it is declared
Procedure scopeAvailable within the procedure in which it is declared
Module scopeAvailable to all code within the module, class, or structure in which it is declared
Namespace scopeAvailable to all code in the namespace in which it is declared
A lifetime of a variable is a period of time during which a variable holds a value. Local variables exists as long as the procedure is executing. After that, they are not available anymore. However, if we declare a variable to be Static, the variable continues to exist after the procedure terminates. Module, Shared and instance variables exist for the lifetime of the application.

The basic example

First, we cover some basics.
Option Strict On


Module Example

    Sub Main()
     
        Console.WriteLine("Simple example")

    End Sub
    
End Module
In this example, we have a Module called Example. Inside the example, we have a Main() subroutine. The statement that prints some message to the console is placed within the Main() procedure. Event the most simple Visual Basic programs must be properly organized.
Option Strict On


Public Class Example

    Public Shared Sub Main()
     
        Console.WriteLine("Simple example")

    End Sub
    
End Class
The exact example, now without the module. We can put the code inside a class too. The Main() procedure must be declared Shared, because the class is not instantiated. The compiler calls the Main() method without creating an instance of the class. That is why it must be declared Shared. Java and C# work the same.

Namespaces

Namespaces are used to organize code at the highest logical level. They classify and present programming elements that are exposed to other programs and applications. Within a namespace, we can declare another namespace, a class, an interface, a struct, an enum or a delegate.
In the following code, we have two files that share the same namespace.
Option Strict On

NameSpace ZetCode

    Module Example1
    
        Public Dim x As Integer = 0
        
        Sub Init()

            x += 100
            Console.WriteLine(x)
        
        End Sub
    
    End Module

End NameSpace
We have a ZetCode namespace. In the namespace, we have a module Example1.
NameSpace ZetCode
We declare a namespace called ZetCode.
Public Dim x As Integer = 0
In the module, we declare and initialize a x variable.
Sub Init()
    x += 100
    Console.WriteLine(x)
End Sub
We have an Init() method, in which we work with the x variable.
Option Strict On

NameSpace ZetCode

    Module Example
     
        Sub Main()
        
            Init()
            x += 100
            Console.WriteLine(x)

        End Sub
    
    End Module
              
End NameSpace
In the second file, we work with the Init() method from the previous file.
NameSpace ZetCode
We work in the same namespace.
Init()
x += 100
Console.WriteLine(x)
We call the Init() procedure and work with the x variable. Both the procedure and the x variable are defined in a different file and different module. But they are defined in the same namespace, so we can use them.
$ ./samenamespace.exe 
100
200
Output.

The following code example has two distinct namespaces. We use the Imports keyword to import elements from a different namespace.
Option Strict On

NameSpace MyMath

    Public Class Basic
    
        Public Shared PI As Double = 3.141592653589
        
        Public Shared Function GetPi() As Double

            Return Me.PI
        
        End Function
    
    End Class

End NameSpace
We have a skeleton of a Math class in a MyMath namespace. In the Basic class, we define a PI constant and a GetPi() method.
Option Strict On

Imports MyMath

NameSpace ZetCode

    Public Class Example
     
        Public Shared Sub Main()

            Console.WriteLine(Basic.PI)
            Console.WriteLine(Basic.GetPi())

        End Sub
    
    End Class
              
End NameSpace
In this file, we use the elements from the MyMath namespace.
Imports MyMath
We import the elements from the MyMath namespace into our namespace.

Root namespace
Figure: Root namespace

On Visual Basic 2008 Express edition, there is a root namespace automatically created. This can be found under project properties, Application tab. Either delete the root namespace or include it into the imports path. For example, if you have Testing there, change the line to Imports Testing.MyMath.
Console.WriteLine(Basic.PI)
Console.WriteLine(Basic.GetPi())
Now we can use those elements. In our case the PI variable and the GetPi() method.
Option Strict On

' Imports MyMath

NameSpace ZetCode

    Public Class Example
     
        Public Shared Sub Main()

            Console.WriteLine(MyMath.Basic.PI)
            Console.WriteLine(MyMath.Basic.GetPi())

        End Sub
    
    End Class
              
End NameSpace
Note, that we do not need the Imports keyword. In the example, it is commented out. We can use elements from other namespaces by using fully qualified names of the elements.

Modules

A module is used to organize code and wrap up variables, properties, events, and procedures of similar use. Unlike a class, a module is not a type. A module can be created in a namespace or in a file. A module cannot be created inside another module, class, structure, interface or block. All members in a module are implicitly Shared. Modules have a Friend access. This means, that a module is accessible everywhere in an assembly.
Option Strict On

Module First

    Public x As Byte = 11

    Public Sub FirstModule()

        Console.WriteLine("First module")

    End Sub

End Module

Module Second

    Public y As Byte = 22

    Public Sub SecondModule()

        Console.WriteLine("Second module")

    End Sub

End Module


Module Example

    Sub Main()
     
        Console.WriteLine(x)
        Console.WriteLine(Second.y)
        FirstModule()
        SecondModule()

    End Sub
    
End Module
We have three modules defined. The first two modules have variables and procedures. These will be used in the third module.
Module First

    Public x As Byte = 11
...
End Module
We can use access specifiers inside modules too. This way we can control the accessibility of the elements in the modules.
Console.WriteLine(x)
Console.WriteLine(Second.y)
We print the x, y variables. They are Public and are accessible from a different module. We may use the module name to fully specify the variable name.

A scope is a visibility of a variable. A variable with a module scope is available within the module, where it was declared.
Option Strict On


Module Example
 
    Private x As Integer = 0

    Sub Main()
              
        proc1()
        proc2()
        proc3()

    End Sub
    
    Sub proc1()
    
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc2()
    
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc3()
    
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
End Module
We have x variable inside the module. The variable is available in all three procedures.
Private x As Integer = 0
This is a variable with a module scope. It is declared outside any procedure.
Sub proc2()
    x += 100
    Console.WriteLine(x)
End Sub
Inside the proc2() procedure, we increase the x variable and print its contents to the console. We refere to the x variable defined in the module.
$ ./modulescope.exe 
0
100
200
Output of the example.

Procedures

Procedures provide modularity to the code project. They should do only a specific task.
Option Strict On


Module Example
 
    Dim x As Integer = 0 
    
    Sub Main()
              
        Console.WriteLine(x)
        
        proc1()
        proc2()
        proc3()

    End Sub
    
    Sub proc1()
    
        Dim x As Integer 
        x += 100
    
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc2()
    
        Dim x As Integer
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc3()
    
        Dim x As Integer
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
End Module
In the preceding code example, we have three procedures beside the main procedure. The three procedures create a local x variable and print it to the terminal. The main procedure refers to the module x variable.
Sub proc1()
    Dim x As Integer 
    x += 100
    Console.WriteLine(x)
End Sub
The proc1() procedure creates a local x variable. This variable shadows the one, declared at a module scope.
$ ./procedurescope.exe 
0
100
100
100
The main procedure prints 0. The other procedures print 100 to the terminal. They create their local x variables, initiate them to 0, increase by 100.

Block scope

It is important to understand that variables declared within a block of code like If/End If or While/End While have a limited block scope and lifetime. The next example illustrates this.
Option Strict On


Module Example

    Sub Main()
             
        If True

            Console.WriteLine("Inside If block")        

            Dim x As Integer = 0
            Console.WriteLine(x)
            
            x += 500
            Console.WriteLine(x)

        End If

        Console.WriteLine("Outside If block")        
        
        Rem Will not compile
        Rem Console.WriteLine(x)

    End Sub
    
    
End Module
We have an x variable declared Inside the If/End If block.
Rem Will not compile
Rem Console.WriteLine(x)
The variable is not available outside the block. If we uncomment the second line, the example will not compile.
This part of the Visual Basic tutorial was dedicated to organizing code. We mentioned basic organizational elements of the code like namespaces, modules or procedures. We described variable scope and duration, which is closely related to those elements.
no image

Procedures & functions In Visual Basic 6.0

 In this part of the tutorial, you will learn Visual Basic procedures & functions.

We use procedures and functions to create modular programs. Visual Basic statements are grouped in a block enclosed by Sub, Function and matching End statements. The difference between the two is that functions return values, procedures don't.

A procedure and function is a piece of code in a larger program. They perform a specific task. The advantages of using procedures and functions are:

    Reducing duplication of code
    Decomposing complex problems into simpler pieces
    Improving clarity of the code
    Reuse of code
    Information hiding

Procedures

A procedure is a block of Visual Basic statements inside Sub, End Sub statements. Procedures do not return values.

Option Strict On


Module Example

    Sub Main()
      
        SimpleProcedure()
       
    End Sub
   
    Sub SimpleProcedure()
        Console.WriteLine("Simple procedure")
    End Sub
   
End Module

This example shows basic usage of procedures. In our program, we have two procedures. The Main() procedure and the user defined SimpleProcedure(). As we already know, the Main() procedure is the entry point of a Visual Basic program.

SimpleProcedure()

Each procedure has a name. Inside the Main() procedure, we call our user defined SimpleProcedure() procedure.

Sub SimpleProcedure()
    Console.WriteLine("Simple procedure")
End Sub

Procedures are defined outside the Main() procedure. Procedure name follows the Sub statement. When we call a procedure inside the Visual Basic program, the control is given to that procedure. Statements inside the block of the procedure are executed.

Procedures can take optional parameters.

Option Strict On


Module Example

    Sub Main()

        Dim x As Integer = 55
        Dim y As Integer = 32
      
        Addition(x, y)
       
    End Sub
   
    Sub Addition(ByVal k As Integer, ByVal l As Integer)
        Console.WriteLine(k+l)
    End Sub
   
End Module

In the above example, we pass some values to the Addition() procedure.

Addition(x, y)

Here we call the Addition() procedure and pass two parameters to it. These parameters are two Integer values.

Sub Addition(ByVal k As Integer, ByVal l As Integer)
    Console.WriteLine(k+l)
End Sub

We define a procedure signature. A procedure signature is a way of describing the parameters and parameter types with which a legal call to the function can be made. It contains the name of the procedure, its parameters and their type, and in case of functions also the return value. The ByVal keyword specifies how we pass the values to the procedure. In our case, the procedure obtains two numerical values, 55 and 32. These numbers are added and the result is printed to the console.
Functions

A function is a block of Visual Basic statements inside Function, End Function statements. Functions return values.

There are two basic types of functions. Built-in functions and user defined ones. The built-in functions are part of the Visual Basic language. There are various mathematical, string or conversion functions.

Option Strict On


Module Example

    Sub Main()
      
        Console.WriteLine(Math.Abs(-23))
        Console.WriteLine(Math.Round(34.56))
        Console.WriteLine("ZetCode has {0} characters", _
            Len("ZetCode"))
       
    End Sub
   
End Module

In the preceding example, we use two math functions and one string function. Built-in functions help programmers do some common tasks.

In the following example, we have a user defined function.

Option Strict On


Module Example

    Dim x As Integer = 55
    Dim y As Integer = 32
   
    Dim result As Integer

    Sub Main()

        result = Addition(x, y)
        Console.WriteLine(Addition(x, y))
       
    End Sub
   
    Function Addition(ByVal k As Integer, _
                       ByVal l As Integer) As Integer
        Return k+l
    End Function
   
End Module

Two values are passed to the function. We add these two values and return the result to the Main() function.

result = Addition(x, y)

Addition function is called. The function returns a result and this result is assigned to the result variable.

Function Addition(ByVal k As Integer, _
                    ByVal l As Integer) As Integer
    Return k+l
End Function

This is the Addition function signature and its body. It also includes a return data type, for the returned value. In our case is is an Integer. Values are returned to the caller with the Return keyword.
Passing parameters by value, by reference

Visual Basic supports two ways of passing parameters to functions. By value and by reference. For this, we have two keywords. ByVal and ByRef. When we pass arguments by value, the function works only with the copies of the values. This may lead to performance overheads, when we work with large amounts of data.

When we pass values by reference, the function receives a reference to the actual values. The original values are affected, when modified. This way of passing values is more time and space efficient. On the other hand, it is more error prone.

Which way of passing arguments should we use? It depends on the situation. Say we have a set of data, salaries of employees. If we want to compute some statistics of the data, we do not need to modify them. We pass by values. If we work with large amounts of data and the speed of computation is critical, we pass by reference. If we want to modify the data, e.g. do some reductions or raises to the salaries, we might pass by reference.

The following two examples cover both concepts.

Option Strict On


Module Example

    Dim a As Byte = 4
    Dim b As Byte = 7

    Sub Main()
      
        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)

        Swap(a, b)

        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
       
    End Sub
   

    Sub Swap(ByVal a As Byte, ByVal b As Byte)
        Dim temp As Byte
        temp = a
        a = b
        b = temp
        Console.WriteLine("Inside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
    End Sub
 
End Module

The Swap() procedure swaps the numbers between the a, b variables. The original variables are not affected.

Dim a As Byte = 4
Dim b As Byte = 7

At the beginning, these two variables are initiated.

Swap(a, b)

We call the Swap() procedure. The procedure takes a, b variables as parameters.

temp = a
a = b
b = temp

Inside the Swap() procedure, we change the values. Note that the a, b variables are defined locally. They are valid only inside the Swap() procedure.

$ ./swap1.exe
Outside Swap procedure
a is 4
b is 7
Inside Swap procedure
a is 7
b is 4
Outside Swap procedure
a is 4
b is 7

The output shows, that the original variables were not affected.

The next code example passes values to the function by reference. The original variables are changed inside the Swap() procedure.

Option Strict On


Module Example

    Dim a As Byte = 4
    Dim b As Byte = 7

    Sub Main()
      
        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)

        Swap(a, b)

        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
       
    End Sub
   

    Sub Swap(ByRef a As Byte, ByRef b As Byte)
        Dim temp As Byte
        temp = a
        a = b
        b = temp
        Console.WriteLine("Inside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
    End Sub
 
End Module

In this example, calling the Swap() procedure will change the original values.

Sub Swap(ByRef a As Byte, ByRef b As Byte)
 ... 
End Sub

Now we use the ByRef keyword to indicate, that we pass parameters by reference.

$ ./swap2.exe
Outside Swap procedure
a is 4
b is 7
Inside Swap procedure
a is 7
b is 4
Outside Swap procedure
a is 7
b is 4

Here we see, that the Swap() procedure really changed the values of the variables.
Recursion

Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition. (Wikipedia) In other words, a recursive function calls itself to do its job. Recursion is a widely used approach to solve many programming tasks.

A typical example is calculation of the factorial.

Option Strict On


Module Example

    Sub Main()
      
        Console.WriteLine(Factorial(4))
        Console.WriteLine(Factorial(10))
       
    End Sub
   
    Function Factorial(ByVal n As UShort) As UShort
        If (n=0)
            Return 1
        Else
            Return n * Factorial(n-1)
        End If
      
    End Function
   
End Module

In this code example, we calculate the factorial of two numbers.

Return n * Factorial(n-1)

Inside the body of the factorial function, we call the factorial function with a modified argument. The function calls itself.

$ ./recursion.exe
24
3628800

These are the results.
Module scope, procedure scope

A scope is the range in which a variable can be referenced. A variable which is declared inside the procedure has a procedure scope. It is valid only in this particular procedure. A variable declared inside a module has a module scope. It is valid everywhere in the module.

Option Strict On


Module Example

    Dim a As Byte = 2

    Sub Main()
        Dim b As Byte = 3        

        Console.WriteLine(a)
        SimpleProcedure()
       
    End Sub
   
    Sub SimpleProcedure()
        Console.WriteLine(a)
        ' Console.WriteLine(b)
    End Sub
   
End Module

In the preceding example, we declare two variables. Variable a has the module scope, variable b has the procedure scope.

Dim a As Byte = 2

Variable a is declared inside the Example module, outside the two procedures. It is valid in both procedures.

Sub Main()
    Dim b As Byte = 3        
...
End Sub

The variable b is declared in the Main() procedure. It is valid only there. It is not valid in the second procedure.

Sub SimpleProcedure()
    Console.WriteLine(a)
    ' Console.WriteLine(b)
End Sub

The statement printing the b variable is commented. If we uncommented the line, the example would not compile.

Option Strict On


Module Example

    Dim a As Byte = 2

    Sub Main()
        Dim a As Byte = 3        

        Console.WriteLine(a)
       
    End Sub
   
End Module

In the preceding example, we have declared a variable with the same name in two different scopes. They do not collide. The variable declared inside the Main() procedure overrides the one, declared in the module scope.

$ ./scope2.exe
3

Output.
Static variables

A static variable is a variable that has been allocated statically, whose lifetime extends across the entire run of the program. (Wikipedia) The default, local variables do not retain their value within consecutive calls of the function.

Option Strict On


Module Example

    Sub Main()
      
        NonStatic()
        NonStatic()
        NonStatic()
        NonStatic()
        Console.WriteLine(NonStatic)
       
    End Sub
   
    Function NonStatic() As Integer
        Dim x As Integer = 0
        x += 1
        Return x
    End Function
   
End Module

In the above example, we have a normal, non-static variable. We increment the variable each time the function is called. We call the function 5 times. However, non-static variables are initiated for each call of the function.

$ ./nonstatic.exe
1

After 5 function calls the x variable equals to 1.

The static variables are initiated only once, when the function is first called. They retain their value afterwards.

Option Strict On

Module Example

    Sub Main()
      
        StaticFunction()
        StaticFunction()
        StaticFunction()
        StaticFunction()
        Console.WriteLine(StaticFunction)
       
    End Sub
   
    Function StaticFunction() As Integer
        Dim Static x As Integer = 0
        x += 1
        Return x
    End Function
   
End Module

After 5 consecutive calls, the x is equal to 5.

Dim Static x As Byte = 0

Static variables are created with the Static keyword.

$ ./static.exe
5

Running the example.

In this part of the Visual Basic tutorial, we covered procedures and functions.

About Us

Powered by Blogger.
Copyright © 2013 Zuhzwan All Right Reserved