Concepts from Variable to Structure to Class

 

July 23, 2010

1. Variable

       A variable contains only one specific entity, such as an integer (i.e. 3), a floating point number (i.e. 3.1416), or a character set (i.e. Good morning!).

2. Structure

       In C, a structure is a collection of variables that are referenced under one name, providing a convenient means of keeping related information together.

       struct addr {                                             // struc is the keyword, it defines a structure type.

               char name [30];                                 // addr is the structure name;

               char street [60];

               char city [20];                                    // city is one of the structure elements.

               char state [2];

               unsigned long int zip;

       } addr_info;                                             // addr_info is the structure variable.

 

       Individual structure elements are referenced (accessed) using structure variable name followed a period (dot operator) plus the structure element name.  For example,

               addr_info.zip = 12345;

3. Class in C++

       C++ can be thought of as “C with class.”  Classes are basically extensions to the structures of C.  The difference is that structure contains only variables (data), while class contain both variables (objects) and functions (methods).  For example,

       class employee {                                              // Class declaration

               private:

                      int id;

                      char name[30];

float wage;

               public:

                      employee(int i, char *n, float w);      // Constructor, a special type of function

                      void print_payinfo(float hrs);           // Member function

       };

 

 

       // Class implementation

       employee::employee(int i, char *n, float w) {

               id = i;     strcpy(name, n);   wage = w;

       }

 

       void employee::print_payinfo(float hrs) {

               printf(“Employee #%d: %s\n”, id, name);

               printf(“Hours worked:  %6.2f\n”, hrs);

               printf(“Amount paid:  $%7.2f\n\n”, wage);

       }

 

       Classes are organized into two parts: (1) A class declaration and (2) A class implementation. 

       You can access the object’s members the same way as in structure variables, such as john.wage.  In addition, you can access the member functions too.  In this manner, we can call a function that belongs to an object.  For example, let’s call the print_payinfo( ) function for john:

       john.print_payinfo(40.0);

4. User-defined objects in JavaScript

       function Car( ) {                               // constructor function

               this.color;                                   // keyword “this” refers to the current object, namely the

               this.brand;                                  // object that is currently being created using new Car( )

               this.horsepower;

               this.price;

       }

 

       myCar = new Car( );                         // creating a new Car object named myCar with the four

                                                                 // properties color, brand, horsepower, and price.

                                                                 // These properties are represented in code as myCar.color,

                                                                 // myCar.brand, myCar.horsepower, and myCar.price.

 

       The example in details is shown below.

       <html>

<body bgcolor = "#AAFFCC">

<script type = "text/javascript">

               // The car constructor

               function Car(color, brand, horsepower, price) {

                      this.color = color;

                      this.brand = brand;

                      this.horsepower = horsepower;

                      this.price = price;

                      this.showBrand = showBrand;

               }

      

               // The showBrand() method of the Car object

               function showBrand() {

                      document.write(this.brand); // Key word "this" refers the current

       }                                                        // (to be created) object, either realcar or dreamcar.

      

               // Create two Car objects

               realcar = new Car("red", "Ford", 160, 15000);

               dreamcar = new Car("pink", "Cadillac", 300, 40000)

      

               document.write("<p> Your dream car is a: ");

               dreamcar.showBrand();

               document.write("<p>Your real car is a: ");

               realcar.showBrand();

</script>              

</body>

</html>

 

5. Object and Class in PHP

       An object is characterized to have both properties (variables) and methods (functions).  An object is created by first create a class.  A class is a blueprint, or an outline, or a template for an object.  The class defines the properties and methods. 

Once an object is created using

       $object_name = new class_name( );

it will possesses the same properties and methods that were defined in the class declaration.

       It is a good practice to separate the class declaration and the object implementation by including the class declaration in a class library file and including the object implementation in a separated viewable file, such as index.php.  For example,

       <?php                                                               // saving as “class.Demo.php

       class Demo {                                                   // defining a class

               public $name;                                           // adding a property (variable)

               function sayHello( ) {                              // adding a method (function)

                      print “Hello $this->name!”;

               }

       }

       ?>

 

       <?php

       require_once(‘class.Demo.php’);

       $objDemo = new Demo( );                      //  creating a object $objDemo in class Demo

       $objDemo -> name = ‘Sam’;

       $objDemo->sayHello( );

?>

 

       Once the object is created using

               $object_name = new class_name( )

all of the characteristics and behaviors defined within the class are made available to the newly instantiated object.  Note that “( )” are added after the class_name.  The property list can be inserted in “( )” to populate the object.  It is important that the sequence of properties in the list should be the same as they were defined in the class declaration.  An example is given below.

<?php

class car {                                                 // Declare a class named “car”.

       public $color;                                    // “$color” is one of the properties in the class.

       public $brand;                                   // “$brand” is another property in the class.

       public $horsepower;

       public $price;

       function show_brand() {                   // Defining a method (function) in the class.

               echo "$this->brand!!!";              // The keyword "this" refers to the current (to be created
                                                                         // based on the class) objects, eather $dreamcar or $realcar.        }                                                        // The property of an object is accessed by

                                                                 // $object_name->property;

                                                                 // Operator “->” is similar to “.” (dot) in JavaSprint

                                                                 //             objactName.property (in JavaScript)

}                                          // "$this" is a special self-referencing variable built in the OOP PHP.

                                           // "$this" represents an object created using the present class
                                                   // declaration.

 

// $dreamcar = new car();                         // Creating an object $dreamcar. This object possesses all
                                                                         // properties and methods defined in the car class.

// $dreamcar->brand = "Cadillac";           // Populating "Cadillac" to the property "brand" of
                                                                         // $dreamcar.

 

// $realcar = new car();

// $realcar->brand = "Ford";

 

$dreamcar = new car("pink", "Cadillac", 300, 40000);  // This is a much better approach to
                                                                                                      // populate properties. 

$realcar = new car("red", "Ford", 160, 15000);                                    

 

echo "Your dream car is a: ";

$dreamcar->show_brand();                      // Invoking function show_brand( ).  The way to access a
                                                                         // function is:               $property_name->function_name( );
                                                                         // This is similar to “propertyName.functionName( )” in
                                                                         // JavaScript.

 

echo "<br />Your real car is a: ";

$realcar->show_brand();

?>

 

Note, the object $dreamcar is created and populated using

       $dreamcar = new car("pink", "Cadillac", 300, 40000);   

This is a much better approach to populate an object than doing the following:

$dreamcar = new car();

$dreamcar->color = “pink”;

$dreamcar->brand = "Cadillac";

$dreamcar->horsepower = 300;

$dreamcar->price = 40000;

 

6. Class-Objects Using Constructor

       An example:

<?php

class employee {

       protected $name;                      

       protected $rate;                         

       protected $hours;

      

       public function __construct($name, $rate, $hours) {    //Note, there are 3 arguments in the constructor.                            $this->set_name($name);

                      $this->set_rate($rate);

                      $this->set_hours($hours);

                      $this->get_rate();

                      $this->payment($rate, $hours);

               }

      

       public function set_name($name) {

                      $this->name = $name;

                      echo "The name of $this->name is set. ";

               }

      

       public function set_rate($rate) {             

                      $this->rate = $rate;                   

                      echo "The rate of $this->rate for $this->name is set. ";

              }

      

       public function set_hours($hours) {

                      $this->hours = $hours;

                      echo "The hours of $this->hours for $this->name is set. ";

               }

      

       public function get_rate() {

                      $rate = $this->rate;

                      echo "The rate of $this->name is $rate. ";

               }

      

       public function payment($rate, $hours) {                                   

                      $wage = $this->rate * $this->hours;

                      echo "Payment for $this->name is $wage. ";

                      echo "<p></p>";

               }

              

       function __destruct() {                                                                       

                      echo "<p>employee class instance destroyed.</p>";

               }

}

 

$john = new employee("John", 66, 88);          // Note, there are 3 parameters in the object "$john".

$mary = new employee("Mary", 60, 80);

$steph = new employee("Steph", 63, 80);

?>

 

The result of this code is:

The name of John is set. The rate of 66 for John is set. The hours of 88 for John is set. The rate of John is 66. Payment for John is 5808.

 

The name of Mary is set. The rate of 60 for Mary is set. The hours of 80 for Mary is set. The rate of Mary is 60. Payment for Mary is 4800.

 

The name of Steph is set. The rate of 63 for Steph is set. The hours of 80 for Steph is set. The rate of Steph is 63. Payment for Steph is 5040.

employee class instance destroyed.

employee class instance destroyed.

employee class instance destroyed.

      

In general,

<?php

class class_name {

       protected $property1;                      

       protected $property2;                      

       protected $property3;

      

       public function __construct($property1, $property2, $property3) {        

                      $this->set_property1($property1);

                      $this->set_property2($property2);

                      $this->set_property3($property3);

                      $this->other_method1();

                      $this->other_method2($argument1, $argument2);

               }

      

       public function set_property1($property1) {          // Defining method “set_property1( )

                      $this->property1 = $property1;

                      // echo "The Property1 of $this->property1 is set. ";

               }

      

       public function set_property2($property2) {          // Defining method “set_property2( )

                      $this->property2 = $property2;               

                      // echo "The Property2 of $this->property2 for $this->property1 is set. ";

               }

      

       public function set_property3($property3) {          // Defining method “set_property3( )

                      $this->property3 = $property3;

                      // echo "The Property3 of $this->property3 for $this->property1 is set. ";

               }

      

       public function other_method1( ) {                // Defining other_method1( )

 

                      ……;

                      ……;

               }

      

       public function other_method2($argument1, $argument2) {          // Defining other_method2( )

                     

                      ……;

                      ……;

               }

              

function __destruct() {                                                                                     

// echo "<p>employee class instance destroyed.</p>";

               }

}

 

$object1 = new class_name(parameter1, parameter2, parameter3);                                

$object2 = new class_name(parameter1, parameter2, parameter3);   

$object3 = new class_name(parameter1, parameter2, parameter3);

……

$objectn = new class_name(parameter1, parameter2, parameter3);

 

 

7. Constant in a Class

       Class math_functions {

              const PI = ‘3.14159265’;

               const E = ‘2.8182818284”;

               const EULER = “0.5772156649”;

               …………

       }

       Class constants can then be called like this:

               echo math_functions::PI;