You are on page 1of 6

learning php 1)php loosly typed language, no need of declaration of datatypes of the variable s.

-hypertext preprocessor -interpreted language -current version 5 - every variable or object name starts with $ - four datatypes allowed:string, integer, float, boolean -use gettype() function to know the datatype of a variable - to get complete information of the variable use var_dump() or print_r()(reduce d format) - echo and print statements used to print the output on the webpage - echo is a php programming language construct, it returns void so can't be used as a part of an expression. - print is a function whose return type is 1. can be used as a part of an expres sion. -<?php ?> -phpinfo() to get the information about the php version.... don't leave it when it is deployed can be used for hacking -phpversion() to know php version; -some magic strings(starts and ends with two underscores) __LINE__ gives the current line number(file is reading) __FILE__ name of the currently accessed file __CLASS__ __METHOD__ __FUNCTION__ __NAMESPACE__ -heterogenous values can be allowed into the array -to make a constant variable use define function define("PI",3.14)(use uppercase for good maintainability and no need of $ while creating or accessing it) - global variables can be created by attaching a keyword global before the varia ble name, only normal values can be set to a global variable no expressions or o utput of the expressions cant be assigned -php variables are case-sensitive -php function names are case-insensitive - array can be created as follows $a=array(1,2,3);(improvement done in php 5) - echo $a[0]" ".$a[1]." " - "." is used as string concatenation operator - use the variable names within double quotes to substitute the value of the var iable - use single quotes within echo or print to print the given string as it is give n. - escape character -\ - automatic type conversion to bigger datatype will be done implicitly - if you need do it explicitly - settype() can be used to do explicitly -function_exists("function name") (returns boolean)to check the compatibility of a function with the current version of the php -strrev() to reverse the string -str_repeat(string,number of times) to print or assign the string given number o f times -strtoupper() convert to uppercase -ucfirst(string) change first letter of a string to uppercase - Functions to reduce the redundancy in the code - Functions once compiled can be executed any number of times - php functions can return any number of values

- can return array of values or merely anything - pass by value, pass by reference both are possible - java only pass by value - global variables declared within the function can be accessed anywhere use car efully - conditional checking can be done in three ways if,switch,? - looping -while,for - static variables same as in C(preserves the last value of the variable) - superglobals _SERVER['HTTP_REFERER'] _GET _POST _REQUEST _SESSION _COOKIE _ENV - access specifiers - 3(public, private, protected) - use include keyword to include another php file(include_once is preferred reas on elimination of duplication if a file imports another file which is already im ported in the main file) - even though a required file is not included execution will be done to eliminat e this use require(require_once preferred) include "abc.php" -function in class called method - class A {} - variables and methods same as in java - constructor can be defined using the function name __construct(parameter list) - destructor __destruct() - class User{ public $rollno; public static $password; } - creation of object $a=new User; $a->rollno(no dollar for rollno); - think that password is a static variable within User class how to access? User::password; -"::" scope resolution operator -$this to access current object properties(this keyword in java) -"self::password" to access static variables from the methods of a class - $this will not work in static methods - extends keyword for inheritance - parent::methodname() to call superclass method from subclass - Constructor chaining present (in the construction of child class object parent class constructor should be called for compleate creation of the object) - scope- which parts of the program will be able to access the variable - method overriding possible - multiple inheritance not possible - $a= new User; $b=new User; $b=$a; change in $b's properties will change original $a's properties. if you d on't want this to be done use clone keyword $b=clone $a($a object properties will be retained even after $b's properties are changed) - normally class declarations will be done in end of the php file - even though you will not do the declarations in the class and create a object

and assign a new value to a variable a new variable will be created(not a good p ractise) - sample array declarations $siva[]="hello";$siva[]="hi"(automatic assignment of indexes will be don e) - simple way $siva=array("siva","krishna") - creation of an associative array- $siva=["siva"=>"krishna","krishna"=>"siva"] - simple way to access an array FOREACH loop foreach($siva as $item){echo $item;} - using foreach to access items in associative array foreach($siva as $item=>$description){echo "$item:$description"} - alternative to foreach(list and each combined with while loop) while(list($item)=each($siva)) echo "$item" - pass an array to list function in the above example each item in siva will be assigned to item and will be printed - while(list($item,$description)=each($siva)) (for accessing an associative arra y) - is_array(arrayname) to check if a variable is an array or not returns boolean value - count(arrayname) returns the length of the array - count(arrayname,1) if array contains some more arrays combined length of all a rrays will be given. if 1 is omitted only the length of outer array will be prin ted - sort(arrayname) used to sort the array(increasing order) sort(arrayname,SORT_NUMERIC) to sort an array of integers sort(arrayname,SORT_STRING) to sort an array of strings - rsort(arrayname) used to sort the array(decreasing order) - shuffle(arrayname) used to randomly organize the elements in the array example: playing cards - explode(delimiter in db quotes,string) compared to split function in java - extract(associative arrays) convert associative arrays such as _GET, _POST to normal variables - extract(_GET) ?q=hithere will become $q="hithere" if already same variables ar e present with different definition they will be overridden be careful to elimin ate this use the following version which adds a given prefix to the variables extract($_GET, EXTR_PREFIX_ALL, 'fromget'); - compact() combine normal variables to associative arrays <?php $fname = "Elizabeth"; $sname = "Windsor"; $address = "Buckingham Palace"; $city = "London"; $country = "United Kingdom"; $contact = compact('fname', 'sname', 'address', 'city', 'country'); print_r($contact); ?> fname=>Elizabeth -reset() looping with foreach loop if you want pointer to be reset to first of t he list reset(arrayname) $item = reset(arrayname) - end() pointer to the last of the list end(arrayname) $last=end(arrayname)

-htmlentities() to prevent injection attacks whatever u type within this functio n will be parsed into textual matter( not harmful to the browser) pointers in c -no explicit type casting required to and from void pointers -no arithmetic on void pointers(cant increment or decrement) unless and otherwis e they are explicitly type casted, ctime error - return more than one value using pass by reference - be cautious while returning the address of a pointer from a function the varia ble's address which u r passing may be dead by that time, use static - #define NULL 0 in(stdlib.h) - every string in c ends with a termination delimiter '\0' u should care about t his there is no length function in c - addition/subtraction of a integer to a pointer means move the pointer forward / backward by N elements. So if an int is 4 bytes big, pa could contain 0x4 on o ur platform after having incremented by 1. - subtraction of a pointer by another pointer means getting their distance, meas ured by elements. So subtracting pb from pa will yield 1, since they have one el ement distance. - only addition and subtraction are supported by pointer variables, multiplicati on and division doesn't make any sense in the world of pointers; - void pointers cant be dereferenced directly - where variables are stored? method variables are stored in stack, global varia bles are constructed in globals sections. - globals, stack, heap, constants, code are the parts of memory - strings are immutable once assigned they cannot be changed - character arrays can be changed they are not immutable - page 53 let us c - If you declare an array argument to a function, it will be treated as a pointe r. - sizeof is an operator - char- 1byte, short- 1 byte int -2bytes float- 4 bytes long - 8 bytes double - 10 bytes - sizeof on an array variable, C is smart enough to understand that what you want to know is how big the array is in memory. - page 59 hfluc - arr[2]=*(arr+2) - arr[0]=*arr - arr contains the address of the first variable in the array - scanf() can cause buffer overflows.... so be sure to limit the length of the s tring while the user is entering scanf("%9s",arr_name); - program may crash or give segmentation fault if u r simply saying scanf("%s",a rr_name); - fgets(food, sizeof(food), stdin); fgets is a good solution to the above proble m it takes the length of the string to be entered as argument so no probs - don't use simple gets() it may lead to big problems; - scanf vs fgets() 1) u should tell to scanf the length of the string u r going to accept otherwise it will throw error or crashes, where as for fgets no need a s it will have size of the char array as argument. 2) u can accept any data at a time %s %d but with fgets u are limited to accept only one string at a time 3) when space is encountered scanf will just accept characters till first space, so if u want to store the entire string use fgets -A good clean fight between these two feisty functions. Clearly, if you need to enter structured data with several fields, you ll want to use scanf(). If you re entering a single unstructured string, then fgets() is probably the way to go.

- char *c="siva" the compiler will put the "siva" variable into the constant mem ory which is read only so u cant write or modify the value, if u want to modify create a copy and assign it to a array char c[]="siva"; char *d=c; - use const char *d so that if you try to modify the value in your code it will throw error. - page 74 - scanf()- scan formatted input - very important page 80 (memory structure) - string.h library for string functions - strstr(first,second) searches for the occurence of second string in the first string - strchr() checks for a given char in a string - strcpy() copy - strcat() concatenate - strlen() find the length of the string - strcmp() compares two strings - http://www.gnu.org/software/libc/manual/html_node/String-and-Array-Utilities.h tml#String-and-Array-Utilities - when we call printf we actually call fprintf(); - fprintf(stdout,"hello world");\ - The fprintf() function allows you to choose where you want to send text to. You can tell fprintf() to send text to stdout (the Standard Output) or stderr (the Standard Error). - scanf() internally calls fscanf() which will take input stream as a parameter - fscanf(stdin,.....) - typically scanf and fscanf are equal - 124 hflc - by default operating system provides you with three streams stdin, stdout, std err and it does not limit us to use these 3 only u can create yourself by using fopen() function call - FILE *out=fopen("output.txt","r/w/a/") - FILE *in=fopen("input.text","r"); - fscanf(in,"%s",arr); - fprintf(stdout,"hello world") - all streams will be closed automatically but it is always good that u close th e streams yourself - fclose(in) fclose(out) - FILE is a macro - Every process can open upto 256 file descriptors. as these are limited be sure to close them so that you will not exhaust - main(int argc,char *argv[]) argc=total number of arguments passed argv=array of character pointers to strings argv[0] will always contain the program name argv[1],argv[2]....... will containt the parameters which we sent along with the file name - its always difficult to have a big source file, "make" resolves this problem b reak the program into smaller chunks and build them using make command - dont put something big into something small - do explicit casting if you want to do so - short i=15; int j=i // no problem int i=1000000; short j=i/////problem unpredictable value short j=(short)i;// good casting is done here - if we lable the variable with unsigned for storing the sign 1 bit is not waste d so you may get the range of the variable doubled - attach long to any other variable to increase the range

- 181 - typedef struct { int cell_no; const char *wallpaper; float minutes_of_charge; } phone; phone p = {5557879, "s.png", 1.35}; - no need of typing the struct name if you want to create structure variables us ing another keyword which is defined using the keyword typedef - a structure can hold another structure reference variable also - access structure members using "." operator - code flexibility and low coupling - call by reference also possible with structure variables - a negative number will be represented in its two's complement form in c - while right shifting a negative number one's will be appended. - to find if N is a fibonacci number or not find if 5n*n+4 or 5n*n-4 is a perfec t square or not.. if perfect square its a fibonacchi number - see word alignment http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/aligned.html

BufferedWriter br=new BufferedWriter(new FileWriter(new File(""))); What this means? Adding more number of responsibilities(wrappers) at run-time. This is typical ex ample for Decorator design pattern... File is decorated with FileWriter which is in turn decorated with BufferedWriter... we are just adding a wrapper on top of each layer. If we want to write a set of characters to a file for every character FileWriter performs IO (writes each byte to hard disk) expensive operations.... so to redu ce this we wrapped it up with BufferedWriter which in turn have a buffer of spec ified size (1024 bytes by default), unless otherwise the buffer is filled, it wi ll not do hard disk I/O so the performance is not effected.... If you don't want to use BufferedWriter you are always welcome to use FileWriter directly..... simply unwrapping... Time to write your own BufferedWriter :D

You might also like