Wednesday, 23 October 2013

Variable scope

Variable scope

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
<?php
$a 
1;
include 
'b.inc';?>
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
<?php
$a 
1/* global scope */
function test()
{
    echo 
$a/* reference to local scope variable */ }
test();?>
This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

The global keyword

First, an example use of global:
Example #1 Using global
<?php
$a 
1;$b 2;

function 
Sum()
{
    global 
$a$b;

    
$b $a $b;
}
Sum();
echo 
$b;?>
The above script will output 3. By declaring $a and $b global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables that can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined $GLOBALS array. The previous example can be rewritten as:
Example #2 Using $GLOBALS instead of global
<?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. Here's an example demonstrating the power of superglobals:
Example #3 Example demonstrating superglobals and scope
<?phpfunction test_global()
{
    
// Most predefined variables aren't "super" and require
    // 'global' to be available to the functions local scope.
    
global $HTTP_POST_VARS;
   
    echo 
$HTTP_POST_VARS['name'];
   
    
// Superglobals are available in any scope and do
    // not require 'global'. Superglobals are available
    // as of PHP 4.1.0, and HTTP_POST_VARS is now
    // deemed deprecated.
    
echo $_POST['name'];
}
?>
Note:
Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

Using static variables

Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope. Consider the following example:
Example #4 Example demonstrating need for static variables
<?phpfunction test()
{
    
$a 0;
    echo 
$a;
    
$a++;
}
?>
This function is quite useless since every time it is called it sets $a to 0 and prints 0. The $a++ which increments the variable serves no purpose since as soon as the function exits the $a variable disappears. To make a useful counting function which will not lose track of the current count, the $a variable is declared static:
Example #5 Example use of static variables
<?phpfunction test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}
?>
Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one which calls itself. Care must be taken when writing a recursive function because it is possible to make it recurse indefinitely. You must make sure you have an adequate way of terminating the recursion. The following simple function recursively counts to 10, using the static variable $count to know when to stop:
Example #6 Static variables with recursive functions
<?phpfunction test()
{
    static 
$count 0;

    
$count++;
    echo 
$count;
    if (
$count 10) {
        
test();
    }
    
$count--;
}
?>
Note:
Static variables may be declared as seen in the examples above. Trying to assign values to these variables which are the result of expressions will cause a parse error.
Example #7 Declaring static variables
<?phpfunction foo(){
    static 
$int 0;          // correct
    
static $int 1+2;        // wrong  (as it is an expression)
    
static $int sqrt(121);  // wrong  (as it is an expression too)

    
$int++;
    echo 
$int;
}
?>
Note:
Static declarations are resolved in compile-time.
Note:
Using global keyword outside a function is not an error. It can be used if the file is included from inside a function.

References with global and static variables

The Zend Engine 1, driving PHP 4, implements the static and global modifier for variables in terms of references. For example, a true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. This can lead to unexpected behaviour which the following example addresses:
<?phpfunction test_global_ref() {
    global 
$obj;
    
$obj = &new stdclass;
}

function 
test_global_noref() {
    global 
$obj;
    
$obj = new stdclass;
}
test_global_ref();var_dump($obj);test_global_noref();var_dump($obj);?>
The above example will output:

NULL
object(stdClass)(0) {
}
A similar behaviour applies to the static statement. References are not stored statically:
<?phpfunction &get_instance_ref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign a reference to the static variable
        
$obj = &new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}

function &
get_instance_noref() {
    static 
$obj;

    echo 
'Static object: ';
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Assign the object to the static variable
        
$obj = new stdclass;
    }
    
$obj->property++;
    return 
$obj;
}
$obj1 get_instance_ref();$still_obj1 get_instance_ref();
echo 
"\n";$obj2 get_instance_noref();$still_obj2 get_instance_noref();?>
The above example will output:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) {
["property"]=>
int(1)
}
This example demonstrates that when assigning a reference to a static variable, it's not remembered when you call the &get_instance_ref() function a second time.

Predefined Variables

Predefined Variables

PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the command line. For a listing of these variables, please see the section on Reserved Predefined Variables.
Warning
In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major change in PHP. Having register_globals off affects the set of predefined variables available in the global scope. For example, to get DOCUMENT_ROOT you'll use $_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.
For related information on this change, read the configuration entry for register_globals, the security chapter on Using Register Globals , as well as the PHP » 4.1.0 and » 4.2.0 Release Announcements.
Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.
From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These new arrays are rather special in that they are automatically global--i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) The superglobals are listed below; however, for a listing of their contents and further discussion on PHP predefined variables and their natures, please see the section Reserved Predefined Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
Note: Variable variables

Superglobals cannot be used as variable variables inside functions or class methods.
Note:
Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not identical, so modifying one will not change the other.
If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also left empty.

php Variables

Note: For our purposes here, a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).
Note: $this is a special variable that can't be assigned.
<?php
$var 
'Bob';$Var 'Joe';
echo 
"$var$Var";      // outputs "Bob, Joe"$4site 'not yet';     // invalid; starts with a number$_4site 'not yet';    // valid; starts with an underscore$täyte 'mansikka';    // valid; 'ä' is (Extended) ASCII 228.?>
By default, variables are always assigned by value. That is to say, when you assign an expression to a variable, the entire value of the original expression is copied into the destination variable. This means, for instance, that after assigning one variable's value to another, changing one of those variables will have no effect on the other. For more information on this kind of assignment, see the chapter on Expressions.
PHP also offers another way to assign values to variables: assign by reference. This means that the new variable simply references (in other words, "becomes an alias for" or "points to") the original variable. Changes to the new variable affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is being assigned (the source variable). For instance, the following code snippet outputs 'My name is Bob' twice:
<?php
$foo 
'Bob';              // Assign the value 'Bob' to $foo$bar = &$foo;              // Reference $foo via $bar.$bar "My name is $bar";  // Alter $bar...echo $bar;
echo 
$foo;                 // $foo is altered too.?>
One important thing to note is that only named variables may be assigned by reference.
<?php
$foo 
25;$bar = &$foo;      // This is a valid assignment.$bar = &(24 7);  // Invalid; references an unnamed expression.function test()
{
   return 
25;
}
$bar = &test();    // Invalid.?>
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.
Example #1 Default values of uninitialized variables
<?php// Unset AND unreferenced (no use context) variable; outputs NULLvar_dump($unset_var);// Boolean usage; outputs 'false' (See ternary operators for more on this syntax)echo($unset_bool "true\n" "false\n");// String usage; outputs 'string(3) "abc"'$unset_str .= 'abc';var_dump($unset_str);// Integer usage; outputs 'int(25)'$unset_int += 25// 0 + 25 => 25var_dump($unset_int);// Float/double usage; outputs 'float(1.25)'$unset_float += 1.25;var_dump($unset_float);// Array usage; outputs array(1) {  [3]=>  string(3) "def" }$unset_arr[3] = "def"// array() + array(3 => "def") => array(3 => "def")var_dump($unset_arr);// Object usage; creates new stdClass object (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) {  ["foo"]=>  string(3) "bar" }
$unset_obj->foo 'bar';var_dump($unset_obj);?>
Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. It is also a major security risk with register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array. isset() language construct can be used to detect if a variable has been already initialized.

Saturday, 20 July 2013

Super Forex EA

 To Know More about this EA please visit SUPER FOREX EA

To Do Download Super Forex EA 

Thursday, 4 July 2013

Sunday, 26 May 2013

Arrays, References, Memory Leaks


                      Arrays are references! 
                      Garbage collection reclaims arrays that can not be accessed! 
                      References are initialized to null 
                      When done with a reference set it to null 

public classArrayExamples{public static void main( String args[] )
{int[] integerArray = new int[ 4 ];integerArray[ 1 ] = 12integerArray = new int[ 2 ]; // Memory Leak - No!integerArray[  1  ]  =  5;int[] aliasForArray = integerArray;aliasForArray[  1  ]  =  10;System.out.println( integerArray[ 1 ] ); //Prints 10}
}
HEAP ALLOCATION
integerArray[ 1 ] = 12
integerArray = new int[ 2 ]; // Memory Leak - No!
integerArray[  1  ]  =  5;
int[] aliasForArray = integerArray;
aliasForArray[  1  ]  =  10;
Memory Problems in C/C++
Memory Leaks
Memory that program has allocated but can no longer access  int* trouble = new int( 5 );

Arrays


Major differences with C/C++ arrays:
Java arrays are references
Java arrays know their size
Java checks the bounds of an array when accessed
Java multidimensional arrays need not be rectangular
Java array elements are initialized

Example 1:)
public class SimpleReferenceExample{public static void main( String args[] )
{// Reference allocated, no array space allocatedfloat[] sampleArray;//allocate array locations on heapsampleArray = new float[ 12 ];// Indexing starts at 0 like C/C++sampleArray[ 0 ] = 3.2F;int[] integerArray = new int[ 3 ];
// Reference refers to new array.// Old array available for garbage collectionsampleArray = new float[ 2 ];}
} Example 2:)
public class ArrayExamples{public static void main( String args[] )
{// Two locations to place [ ]int integerArray[ ];int[ ] alias;integerArray = new int[ 10 ]; // Indexed from 0 to 9// Note use of .length to get array sizefor ( int index = 0; index < integerArray.length; index++ )
integerArray[  index  ]  =  5;alias = integerArray; // Arrays are referencesalias[  3  ]  =  10;System.out.println( integerArray[ 3 ] ); //Prints 10
integerArray = new int[ 8 ];System.out.println( integerArray[ 3 ] ); //Prints 0, Why?System.out.println( alias[ 3 ] ); //Prints 10System.out.println( integerArray ); //Prints [I@5e300868}}

Casting


class Casting{public static void main( String args[] )
{int anInt = 5;float aFloat = 5.8f;aFloat = anInt; // Implicit casts up are okanInt = aFloat ; // Compile error,
// must explicitly cast downanInt = (int) aFloat ;float error = 5.8; // Compile error, 5.8 is doublefloat works = ( float) 5.8;char c = (char) aFloat;double aDouble = 12D;double bDouble = anInt + aDouble; // anInt is cast upto double,int noWay = 5 / 0; // Compile error, compiler detects
// zero divideint zero = 0;int trouble = 5 / zero; //Some compilers may give error hereint notZeroYet;notZeroYet = 0;
 trouble = 5 / notZeroYet ; // No compile error!}}
Ints and Booleans are Different
class UseBoolean {public static void main( String args[] )
{if ( ( 5 > 4 ) == true )System.out.println( "Java's explicit compare " );if ( 5 > 4 )System.out.println( "Java's implicit compare " );if ( ( 5 > 4 ) != 0 ) // Compile errorSystem.out.println( "C way does not work" );boolean cantCastFromIntToBoolean = (boolean) 0;
// compile errorint  x  =  10;int  y  =  5;if ( x = y ) // Compile error

System.out.println( "This does not work in Java " );}} 

Basic Data Types


class PrimitiveTypes{public static void main( String args[] )
{// Integral Typesbyte aByteVariable; // 8-bitsshort aShortVariable; // 16-bitsint aIntVariable; // 32-bitslong aLongVariable; // 64-bits// Floating-Point Typesfloat aFloatVariable; // 32-bit IEEE 754 floatdouble aDoubleVariable; // 64-bit IEEE 754 float// Character Typechar aCharVariable; // always 16-bit Unicode// Boolean Typesboolean aBooleanVariable; // true or false}}
Operations on Primitive Types

class Operations{public static void main( String args[] )
{int a = 2;int b = +4;int c = a + b;if ( b > a )
System.out.println("b is larger");else
System.out.println("a is larger");System.out.println( a << 1); // Shift left: 4System.out.println( a >> 1); // Shift right: 1System.out.println( ~a ); // bitwise negation: -3System.out.println( a | b); // bitwise OR: 6System.out.println( a ^ b); // bitwise XOR: 6System.out.println( a & b); // bit

Guide to JAVA

CLASSPATH
Java uses the environment variable CLASSPATH to locate class libraries
• .class files those needed to compile or run the program it searches from
CLASSPATH
By default class path consists only the current directory but you can provide them in –classpath option of javac or include directories in CLASSPATH environment variables.
Example classpath = . ; c:\java\lib; c:\csi211\lab


Some Basic Java Syntax
Java Comments
/* Standard C comment works  */
// C++ comment works
/** Special comment for documentation – java comments */
class Syntax
{ public static void main( String args[] ){
int aVariable = 5;double aFloat = 5.8;
if ( aVariable < aFloat )System.out.println( "True" );
int b = 10; // This is legal in Javachar c;c = 'a';
}}
Java Program Style and Layout
Three different indentation styles you can use
You can pick a reasonable indentation style and use it consistently in your programs

Style#1
class Syntax { // brace starts from here
public static void main( String args[] ) {int aVariable = 5;if ( aVariable < aFloat )
System.out.println( "True" );}}
Style #2
class Syntax
{ // brace startspublic static void main( String args[] ){
int aVariable = 5;if ( aVariable < aFloat )System.out.println( "True" );}}
Style#3
class Syntax{// brace startspublic static void main( String args[] )
{int aVariable = 5;if ( aVariable < aFloat )
System.out.println( "True" );}}
Naming conventions
Class Naming Uses Capitalized word(s) i.e. Title case
Examples:-   HelloWorld, MyList, StudentMark
Wrong: helloWorld,  HW (do not use abbreviat

An Example HelloWorld


/**    This is my first java program */
public class HelloWorldExample
{ public static void main( String args[] ){
System.out.println("Hello World");}}

Java Source Code Naming Conventions
All java source file should end in .java
Each .java file can contain only one public class
The name of the file should be the name of the public class plus ".java"
Do not use abbreviations in the name of the class
If the class name contains multiple words then capitalize the first letter of each word ex. HelloWorld.java

Java - The Platform


Java has a large API (application programming interface) covering a wide range of areas The following list of Java APIs and applications from Sun show the range of applications of Java . For reference http://java.sun.com/products/index.html
Java Foundation Classes (JFC) - GUI
JDBC Database Access
JavaBeans - componentware
Java Web Server
EmbeddedJava - Java on embedded devices


JAVA IDE
Using JDK you can compile and run java program from command line.
 javac HelloWorld. java  - compiling here and it will produce HelloWorld.class i.e. bytecode.
java HelloWorld  - It runs java byte code on native machine
Creating, Compiling, Debugging and Execution for these four steps JDK is not user friendly. IDE is provided for that. A list of IDEs are:
 Eclipse  - from IBM
 Netbeans.

United International University Course Outline

Trimester: Spring 2013
Course: CSI 211
Course Title: Object-oriented Programming
Faculty: Md. Faisal Kabir
Email: faisal@cse.uiu.ac.bd
Assessment:
Component Marks(%)
Attendance 5
Continuous Assessment - Class test 10
Continuous Assessment - Assignment 15
Midterm Examination 30
Final Examination 40
Total 100
Reference Book
• The Complete Reference Herbert Schieldt Java 2.0
• The Java Programming, Deitel and Deitel
This document is prepared by : Dr. S M Monzurur Rahman, Professor, dept. of CSE,UIU
Week 1
Lecture 1
Fundamental of Programming; Java Introduction; Basic Java Syntax: IO
Basic Data Types, Primitive Type Ranges, Operations on Primitive Types, NaN
and Infinity, Casting Default Values of Variables.
Lecture 2
Arrays; Multidimensional Arrays; Some JDK Array Features; Strings: Strings are
Constant!, Strings Reading Command Line Arguments; Control Structures; Jump
Statements; Methods (Functions); Final Variables.
Week 2
Lecture 1
Classes: Fields, Methods; Initializing Fields; Direct Assignment; Instance
Initialization Blocks; Constructors; Overloading Methods; this ;Finalize; Access
Levels for Fields and Methods; Class Names, Packages, Import, CLASSPATH.
Lecture 2
Class members; variables References ; Static, recursion.
• Class Test -1
2
Week 3
Lecture 1
Object oriented concept, Information hiding; examples.
Lecture 2
Inheritance; Class Object; Inheritance and Name Clashes; Super; Constructors
and Inheritance; Static Methods; Access Levels and Inheritance; Inheritance and
Final; Abstract Classes; Relationships between Classes: Is-kind-of, is-a, is-a-typeof
is-analogous-to is-part-of or has-a.
Week 4
Lecture 1
Class Test -2
Interfaces; Clone; Abstract method; Abstract method vs interfaces.
Lecture 2
Java collections.
Week 5
Lecture 1
Exceptions Handling; Java IO
Lecture 2
Nested and Inner Classes.
Week 6
Mid Exam
Week 7
Lecture 1
Threads;
Lecture 2
Generics
Week 8
Lecture 1
Problem Solving – Class Participation (no lecture notes)
Lecture 2
Serialization; Making an Object Serializable; Serializable objects can contain
other objects; Saving and Recovering; Non-Serializable Fields – transient;
Customizing Deserialization; Customizing Serialization; Class Versions; Serial
version.
3
Week 9
Lecture 1
Class Test -3
Internationalization;
Lecture 2
Java Foundation Classes, Java Graphics.
Week 10
Lecture 1
Layouts: Flow layout, Grid layout, border lay out card layout
Events, Event Handling, Containers.
Lecture 2
Class Participation (Problems will be given and solutions will be asked to students,
Class Test-4 equivalent)
Week 11
Lecture 1
GUI Components
Lecture 2
Applet;
Week 12
Lecture 1
More about applets
Lecture 2
Class Test -4
A variety of examples on Applets part1
Week 13
Lecture 1
Architecture Design Pattern; Model-View in Java.
Lecture 2
• Summarization
END OF SEMESTER!!! ENJOY!!!