Difference between revisions of "Object Oriented Programming with Visual Basic"

From Techotopia
Jump to: navigation, search
(Calling Object Methods)
(PHP Object Serialization)
Line 165: Line 165:
 
The result will a message which reads "John Smith has balance of 1225", since the account fee has now been subtracted from the balance.
 
The result will a message which reads "John Smith has balance of 1225", since the account fee has now been subtracted from the balance.
  
== PHP Object Serialization ==
 
  
One of the interesting features of object oriented programming is the ability to take a snapshot of the current state of an object and then save that object to a file, or even transmit it over a network to another process where it will be re-activated. This concept is known in the object oriented world as ''object serialization''.
 
 
All objects have built-in method called ''__sleep'' that is called before serialization. If you need your object to perform any housekeeping before being serialized you will need to override this method.
 
 
An object is serialized using the ''serialize()'' function and unserialized, not surprizsingly, using the ''unserialize()'' function. As an example we can serialize our bankAccount object:
 
 
<pre>
 
<?php
 
class bankAccount {
 
 
  private $accountNumber;
 
  private $accountname;
 
 
  public function __construct($acctNumber, $acctName) {
 
        $this->accountNumber = $acctNumber;
 
        $this->accountname = $acctName;
 
  }
 
 
  public function __destruct() {
 
  }
 
 
  public function setAccountNumber($acctNumber)
 
  {
 
      $this->accountNumber = $acctNumber;
 
  }
 
 
  public function setAccountName($acctName)
 
  {
 
      $this->accountName = $acctName;
 
  }
 
 
  public function getAccountName()
 
  {
 
      return $this->accountName;
 
  }
 
 
  public function getAccountNumber()
 
  {
 
      return $this->accountNumber;
 
  }
 
 
}
 
 
        $myObj = new bankAccount('246810', 'Morgan Freeman');
 
 
        $serialized = serialize ($myObj);
 
 
        echo 'Object is serialized<br>';
 
 
        $newObj = unserialize ($serialized);
 
 
        echo 'Object is unserialized<br>';
 
 
        print_r ($newObj);
 
?>
 
</pre>
 
 
In the above example the object is serialized, then unserialized to a new object variable. We then use the ''print_r()'' function to verify the new object contains everything the old one did resulting in the following output:
 
 
<tt>
 
Object is serialized<br>
 
Object is unserialized<br>
 
bankAccount Object ( [accountNumber:private] => 246810 [accountname:private] => Morgan Freeman )<br>
 
</tt>
 
 
Once we have the serialized data in our $serialized we can do anything we want with it, such as write it to a file or send it through a network socket to another process where it can be unserialized and used.
 
  
 
== Getting Information about a PHP Object ==
 
== Getting Information about a PHP Object ==

Revision as of 18:15, 8 August 2007

Visual Basic provides extensive support for developing object-oriented Windows applications. The subject area of object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. As such, a detailed overview of object oriented software development is beyond the scope of Visual Basic Essentials. Instead, we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to Visual Basic application development.


Contents


What is an Object?

An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application.

Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.

What is a Class?

Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be.


Defining a Visual Basic Class

Before an object can be instantiated we first need to define the class 'blueprint' for the object. In this chapter we will create a bank Account class to demonstrate the concepts of Visual Basic object oriented prorgamming.

Being by starting Visual Studio and creating a new Windows Application named vbObjects. Once the project opens, select the Project... menu and select Add class.... In the Add New Item dialog, name the new class file clsBankAccount.vb and click on the Add button.

Visual Studio will now add a new tab to code area for the new class file containing the following class declaration:

Public Class clsBankAccount

End Class

We have now defined a class. The next step is add some functionality to the class.

Creating Visual Basic Class Properties

Class members or properties are essentially variables embedded into the class. Members can be Public or Private.

Public members can be accessed from outside the object. Private members can only be accessed by methods contained in the class. This the key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters).

We can now extend our BankAccount class to add member variables to hold the account name and number. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as Private:

Public Class clsBankAccount
    Private strAccountNumber As String
    Private strAccountName As String
    Private intBalance As Integer
    Private accountFee As Integer = 5

End Class

Now that we have defined the properties of our class, the next task is to define methods that will give us access to our data.

Defining Class Methods

Since we have declared our our class data properties to be private, we need to provide methods which will give us access to those properties from our code. This is achieved using Get and Set methods. The syntax for get and Set methods is as follows:

Public Property propertyName() As datatype
   Get
     .... Code to return property value
   End Get

   Set(ByVal value As datatype )
     .... Code to return property value
   End Get

To demonstrate this we will add to our class to provide methods to get and set the account number and name. Note that after you type in the Public Property line of the declaration, Visual Studio automatically creates a template for the Get and Set methods, which should be filled in as follows:

Public Class clsBankAccount
    Private strAccountNumber As String
    Private strAccountName As String
    Private intBalance As Integer
    Private accountFee As Integer = 5

    Public Property AccountName() As String
        Get

        End Get
        Set(ByVal value As String)

        End Set
    End Property

    Public Property Balance() As Integer
        Get
            Return intBalance
        End Get
        Set(ByVal value As Integer)
            intBalance = value
        End Set
    End Property
End Class

Now that we have defined our getter and setter methods we can add our own method to perform task. This is the same as writing a Visual Basic function. The purpose of our method will be to subtract the account fee from the current balance:

    Public Function subtractFee() As Integer
        intBalance = intBalance - intAccountFee
        Return intBalance
    End Function

When called, the above function subtracts the account fee from the balance, assigns thje new balance the intBalance variable and returns the new total.

Now that we have added some functionality to our class it is time to instantiate objects from the class blueprint.

How is an Object Instantiated from a Class?

The process of creating an object from the class 'blueprint' is called instantiation. Essentially, you instantiate an instance of the class and give that instance a name by which you will refer to it when accessing members and calling methods. You can create as many object instances of a class as you desire. Objects are instantiated from a class using the new keyword. Visual Basic provides two ways to instantiate an object from a class. These two alternatives are known as late-binding and early binding.

Late binding occurs when the assignment of the object to the variable occurs at run-time when execution reaches the code where the object is created. There are drawbacks to this approach in that any syntax checking is not performed until the application runs because the compiler has no way of checking whether you are referencing valid class members, resulting in potential run-time exceptions. Another disadvantage is that execution can be slowed when using late-binding since much of the work performed by the compiler when using early binding has to be performed at runtime.

Late binding is achieved using the new keyword as follows:

Dim objBankAccount As Object

objBankAccount = New clsBankAccount()

Early binding, on the other hand, has none of the draw backs of late-binding. The compiler performs syntax checks to ensure the object is being used correctly and execution speed is increased because the binding takes place at compile time - not at run-time.

Early binding is performed as follows:

Dim objBankAccount As clsBankAccount

objBankAccount = New clsBankAccount


It is also possible to instantiate the object at the same time that it is declared:

Dim objBankAccount As New clsBankAccount()

Calling Object Methods

Now that we know how to write a class and instantiate objects from the class, we now need to know how to call the methods on the methods we created in the class. First, you will recall that we created Get and Set functions the data members of our class. Because we did this, we can change and access these properties simply by reference them as we would any other property. For example:

Dim objBankAccount As New clsBankAccount()

objBankAccount.AccountName = "John Smith"

objBankAccount.Balance = 1230

MessageBox.Show(objBankAccount.AccountName & " has a balance of " & CStr(objBankAccount.Balance))

The above code excerpt assigns values to the AccountName and account balance properties of our object. It then references the properties in order to display a string with reads "John Smith has balance of 1230" in a MessageBox.

We can also call our subtractFee() method as follows:

Dim objBankAccount As New clsBankAccount()
Dim intNewbalance As Integer

objBankAccount.AccountName = "John Smith"
objBankAccount.Balance = 1230

intNewbalance = objBankAccount.subtractFee()

MessageBox.Show(objBankAccount.AccountName & " has a balance of " & CStr(objBankAccount.Balance))

The result will a message which reads "John Smith has balance of 1225", since the account fee has now been subtracted from the balance.


Getting Information about a PHP Object

There are number of ways to find out information about classes.

An array of classes to which your script has access can be obtained using the get_declared_classes() function. The class_exists() function can be passed the name of a class to find out if such a class exists. A list of methods in a class can be obtained by passing the class name through to the get_class_methods() function.

It is also possible to find out if a class has a parent class using the get_parent_class() function which will either return the name of the parent class, or an empty string if no parent exists.

The method_exists() function, when passed an object pointer and method name as arguments, will return a true or false value indicating the existence of the method.