Pages

Wednesday, October 27, 2010

Design a class

     There is a golden rule in designing a class: keep to real-world thinking. Although that rule sounds simple, it's quite nebulous - what is real-world thinking? There are a number of rules we can follow to keep our code particularly readable:

• We can start or end local variables with a special character so that we are always clear about what variable is being set. The most common method is to start local variables with an underscore, e.g. _Name, _Age, etc.

• To strictly follow OOP guidelines, nearly all variables should be either private or protected - they should not be accessible from outside of an object.

• We can put accessor functions to set and get private variables. To get a variable called _Age, we can define a function Age(). To set a variable called _Age, we can define a function SetAge().

• We can put variables and functions as low down in our inheritance as they can go without repetition - if we find one object has variables and functions it is not supposed to have, we have gone wrong somewhere. For example, while dolphins can swim, gorillas cannot, so we should not put a swim() function into a mammal class "just to save time".

• Muir's law is important in this regard: "When we try to separate anything out by itself, we find it hitched to everything else in the universe". We should keep our classes distinct and separate from each other to begin with rather than try to hack them apart later on.

     If we are wondering why it is that accessor functions should be used to read and write variables, it is because OOP practice dictates that objects should be self-contained - other parts of our program should be able to work with them using simple function calls. For example, imagine we are programming a strategy game where players can control multiple cities. Each city brings in various amount of food depending on how many workers are there. Now, if the player changes the number of workers in a city to 800, we could just effect the change with code like this:

$City->_Workers = 800;

     However, how would that make any change to the amount of food coming in? It wouldn't, so we would need to make your code this:

$City->_Workers = 800;
$City->_FoodSurplus = WORKER_SPEED * 800;

     Now, what if a few weeks later we decide that people can upgrade their cities to build farms and processing facilities that increase the amount of food being made? We'd have to search through our code for all the times we change the _FoodSurplus variable. Later, if we want to make more changes, we need to repeat the procedure again and again and again - the calling code needs to have explicit knowledge of how to handle changes to the number of workers in a city.

     This is not how OOP works. In the OOP world, a city would be supposed to handle all these calculations itself, leaving the calling code looking like this:

City->SetWorkers(800);

    The SetWorkers() function would contain all the other changes such as altering the _FoodSurplus level, but the key is that the calling code wouldn't need to know anything about that - any changes to the SetWorkers() calculation only needs to be made in one place.

Thursday, September 30, 2010

Essential Box Model In CSS


The box model is one of the cornerstones of CSS and dictates how elements are displayed and, to a certain extent, how they interact with each other. Every element on the page is considered to be a rectangular box made up of the element’s content, padding, border, and margin. 



Padding is applied around the content area. If we add a background to an element, it will be applied to the area formed by the content and padding. As such, padding is often used to create a gutter around content so that it does not appear flush to the side of the background.

Adding a border applies a line to the outside of the padded area. These lines come in various styles such as solid, dashed, or dotted. Outside the border is a margin. Margins are transparent and cannot be seen. They are generally used to control the spacing between elements.


Padding, borders, and margins are optional and default to zero. However, many elements will be given margins and padding by the user-agent stylesheet. We can override these browser styles by setting the element’s margin or padding back to zero. We can do this on a case-by-case basis or for every element by using the universal selector:

* {
margin: 0;
padding: 0;
   }

In CSS, width and height refer to the width and height of the content area. Adding padding, borders, and margins will not affect the size of the content area but will increase the overall size of an element’s box. If we wanted a box with a 10-pixel margin and a 5- pixel padding on each side to be 100 pixels wide, we would need to set the width of the content to be 70 pixels.

#myBox

 {
margin: 10px;
padding: 5px;
width: 70px;
}
  


Padding, borders, and margins can be applied to all sides of an element or individual sides. Margins can also be given a negative value and can be used in a variety of techniques.

A box can contain any number of other boxes, creating a hierarchy of boxes that corresponds to the nesting of page elements. The browser window serves as the root element for this hierarchy.

There are two basic types of boxes, block and inline. Block boxes are generated by elements such as P, DIV or TABLE. Inline boxes are generated by tags such as B, I or SPAN and actual content like text and images.

The box type may also be set using the display property. Setting a value of block on an inline element, for example, will cause it to be treated as a block element. Note that if we set the display to none, no box is created. The browser acts as if the element did not exist. Likewise, any nested elements are ignored as well, even if they specifically declare some other display value.
 

Sunday, September 19, 2010

Using $this


Inside a class, $this is a special variable that refers to the properties of the same class. $this can’t be used outside of a class. It’s designed to be used in statements inside a class to access variables inside the same class.

The format for using $this is the following:

 $this-> variable name;

For example, in a Car class that has an attribute $gas, we would access $gas in the following way:

$this->gas;

Using $this refers to $gas inside the class. We can use $this in any of the following statements as shown:

$this->gas = 20;

if($this->gas > 10)

$product[$this->size] = $price;

As we can see, we use $this-> variable name in all the same ways we would use $varname.

Notice that a dollar sign ($) appears before this but not before gas. Don’t use a dollar sign before gas — as in    $this->$gas — because it changes statement’s meaning. We may or may not get an error message, but it isn’t referring to the variable $gas inside the current class.

Friday, September 17, 2010

Objects and classes

OOP was designed to allow programmers to more easily model their programs upon real world scenarios - programmers literally define things (objects) in their world (program), set a few basic properties, then ask them to do things.

The basic elements of object-oriented programs are objects. It’s easiest to understand objects as physical objects. For example, a car is an object. A car has properties, such as color, model, engine, and tires, also called attributes. A car has things it can do, too, such as move forward, move backward, park, roll over.
In general, objects are nouns. A person is an object. However, objects are not just physical objects. Often objects, like nouns, are more conceptual. For example, a bank account is not something we can hold in our hand, but it can be considered an object. A file is often an object. E-mail messages, addresses, songs, TV shows, meetings, and dates can all be objects.

A class is the script that serves as the template, or the pattern, that is used to create an object. The class defines the properties, the attributes, of the object. It also defines the things the object can do — its responsibilities. For example, we write a class that defines a car as four wheels and an engine and lists the things it can do, such as move forward and park. Then, given that class, we can write a statement that creates a car object. Our new car is created following the pattern in our class. When we use our car object, we may find that it is missing a few important things, like a door or a steering wheel or a reverse gear. That’s because we left those out of the class when we wrote it.
A class is a package containing two things: data and methods to access and modify that data. The data portion consists of variables; they're known as properties. The other part of a class is a set of functions that can alter a class properties; they're called methods.

As the person who writes a class, we know how things work inside the class. But it’s not necessary to know how an object accomplishes its responsibilities in order to use it; anyone can use a class. We have no clue how a telephone object works, but we can use it to make a phone call. The person who built the telephone knows what’s happening inside it. When there’s new technology, the phone builder can open the phone and improve it. As long as he doesn’t change the interface — the keypad and buttons — it doesn’t affect our use of the phone at all.

When we define a class, we don't define an object that can be accessed and manipulated. Instead, we define a template for an object. From this blueprint, we create malleable objects through a process known as instantiation.

A program can have multiple objects of the same class, just as a person can have more than one book or many pieces of fruit. Classes also live in a defined hierarchy. At the top of the chain, there is a generic class. Each class down the line is more specialized than its parent. For example, a parent class could be a building. Buildings can be further divided into residential and commercial. Residential buildings can be further subdivided into houses and apartment buildings, and so forth. Both houses and apartment buildings have the same set of properties as all residential buildings, just as residential and commercial buildings share some things in common.

When classes are used to express these parent-child relationships, the child class inherits the properties and methods defined in the parent class. This allows you to reuse the code from the parent class and requires you to write code only to adapt the new child to its specialized circumstances. This is called inheritance and is one of the major advantages of classes over functions. The process of defining a child class from a parent is known as subclassing or extending.

Classes in PHP are easy to define and create:



Class Demo
   {
       Function sayHello($name)
           {
              Print " Hello $name.";
         }
   }


The class keyword defines a class, just as function defines a function. Method declaration is identical to how functions are defined.

Creating an object is as follows.

$objDemo= new Demo;


The new keyword instantiates an object $objDemo from Demo class.

Tuesday, September 14, 2010

Local vs Global Variable Scope


Variable Scope is an important issue in any programming language. Php is not an exceptional in this case. Each variable has an area in which it exists, known as its scope. When we declare a variable outside a function or an object, it may not be seen in the function or object. When we declare a variable inside a function or an object, it may not be seen outside the function or object. That feature is called variable scope. It is technically possible for a PHP script to have several variables called $a in existence at one point in time, however there's only one active $a at any one time.
Any variables not set inside a function or an object are considered global - that is, they are accessible from anywhere else in the script that is not inside another function or an object. Any variable used inside a function is by default limited to the local function scope. In PHP global variables must be declared global inside a function if they are going to be used in that function.

Consider the following code:

<?php
            $a = 4;
            function sendValue()
                        {
                           $a;
                           echo $a;
                        }
            echo "Value of variable outside is ";
            echo $a; echo ".<br />";
            echo "Value of variable inside is";
            sendValue();
?>
In PHP, any variable declared outside a function as $a above, is a global variable. In PHP any variable declared inside a function (see above), is a local variable. In the above code, the $a declared outside the function and the $a declared inside the function are entirely two different things.

Output of the above code:
Value of variable outside is 4.
Value of variable inside is


As we can see from the result, the two variables, though having the same name, but by the fact that one is outside the function and the other is inside, would hold different values. The one inside the function in this case, did not even acquire a value.



If we want the variable declared outside a function to hold the same value as the one inside the function, we have to re-declare the one inside the function, preceding it with the reserved word, global, as in the following code:
  
<?php
            $a = 4;
            function sendValue()
                        {
                                    global $a;
                                    echo $a;
                        }         
            echo "Value of variable outside is ";
            echo $a; echo ".<br />";
            echo "Value of variable inside is  ";
            sendValue();
?>

Output of the above code:



Value of variable outside is 4.
Value of variable inside is 4


From the result, the two values displayed are the same. This illustrates the use of the reserved word, global.

PHP has variables called super global variables, or simply, Superglobals. These are variables that can be seen outside and inside functions without the use of the reserved word, global. The programmer is not allowed to declare such variables. There are only some of them available and they are predefined. Examples of superglobals are the $_POST and $_GET variables. These are actually arrays, not variables.

Superglobals cannot be used as variable variables inside functions or class methods.

A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array.



Example 

<?php
  $a = 1;
  $b = 2;

  function Sum()
  {
     $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
  }

  Sum();
  echo $b;
?>
The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element. Notice how $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal.






Monday, September 06, 2010

Magical foreach loop

The foreach loop takes an array and loops through each element in the array without the need for a test condition or loop counter. As it steps through each element in the array it temporarily stores the value of that element in a variable.


This loop is useful for the array which is consist of unknown number of element. It iterates until the end of the array. The loop has two formats,


First

Foreach(($ArrayName As $ArrayItem)
{
Execute the contents of these braces;
}


This means that for each item in the array, it will iterate around the loop. “$ArrayName” is the name of the array. We can take any name for the “$ArrayItem” variable. If we echo $ArrayItem variable, we will get the values of the array named “ArrayName”.



Second

Foreach($ArrayName As $ArrayIndexValue=>$ArrayItem)
{
Execute the contents of these braces
}


This is the same as the first format, but it makes the array index value available as well. The first argument is the array name. The second and third arguments are variable names that we create our self to hold the index value and the corresponding element in the array.


There might also be missing entries in the array, but it doesn’t have to check every index value, only the elements that contain values. Assume, we have an array named “$states_of_the_USA” , which has 50 elements . We could include the following code, which adds a new element to the array of states:

$states_of_the_USA[100]=”Atlantis”;

Then if we performed the foreach loop, it would be able to add this value to the end of the web page without needing to check through elements 50-99.



Some examples...


Code


<?php

$a = array (1, 2, 3, 17);

$i = 0;

foreach ($a as $v)

{
   echo "\$a[$i] => $v.\n<br>";
   $i++;
}

?>


Out put

$a [0] => 1.
$a [1] => 2.
$a [2] => 3.
$a [3] => 17.





Code



<? php

$a = array ("one" => 1,"two" => 2,"three" => 3,"seventeen" => 17);

foreach ($a as $k => $v)

{
   echo "\$a[$k] => $v.\n<br>";
}

?>

Out put

$a [one] => 1.
$a [two] => 2.
$a [three] => 3.
$a [seventeen] => 17.


Code


<?php

foreach (array(1, 2, 3, 4, 5) as $v)
 {
      echo “$v <br>”;
 }

?> 


Out put

1
2
3
4
5




Foreach loop is also very useful for multi dimensional array. Here is an example


Code


<?php

$a = array ();
$a [0][0] = “a”;
$a [0][1] = “b”;
$a [1][0] = “y”;
$a [1][1] = “z”;

foreach ($a as $v1)

{
   foreach ($v1 as $v2)
  
   {
       echo “$v2\n<br>”;
   }
}

?>




Output

a
b
y
z



Foreach works only on arrays, and will issue an error when we try to use it on a variable with a different data type or an uninitialized variable.