Friday, September 7, 2012

PHP Function array_diff_ukey()

Syntax

array_diff_ukey ( $array1, $array2 [, $array3...,callback $key_compare_func] );

Definition and Usage

Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.
Unlike array_diff_key() an user supplied callback function is used for the indices comparision, not internal function.

Paramters

ParameterDescription
array1Required. The first array is the array that the others will be compared with.
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array
key_compare_funcRequired. callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Example

Try out following example:
<?php
function key_compare_func($v1,$v2) 
{
if ($v1===$v2)
 {
 return 0;
 }
if ($v1>v2)
 {
 return 1;
 }
else
 {
 return -1;
 }
}
$array1 = array(0=>"banana", 1=>"orange", 2=>"grapes");
$array2 = array(3=>"apple",1=>"apricot", 5=>"mango");
print_r(array_diff_ukey($array1,$array2,"key_compare_func"));
?> 
This will produce following result:
Array ( [0]=>banana [2]=>grapes )

PHP Function array_diff_uassoc()

Syntax

array_diff_uassoc ( $array1, $array2 [, $array3..., callback $key_compare_func] );

Definition and Usage

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.
Unlike array_diff_assoc() an user supplied callback function is used for the indices comparision, not internal function.

Paramters

ParameterDescription
array1Required. The array to compare from
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array
key_compare_funcRequired. callback function to use. The callback function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Example

Try out following example:
<?php
function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}
$array1 = array("a" => "green", "b" => "brown", 
                                    "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);

?> 
This will produce following result:
Array ( [b] => brown [c] => blue [0] => red )

PHP Function array_diff_key()

Syntax

array array_diff_key ( array $array1, array $array2 [, array $...] );

Definition and Usage

Compares array1 against array2 and returns the difference.

Paramters

ParameterDescription
array1Required. The first array is the array that the others will be compared with.
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array

Return Values

Returns an array containing all the entries from array1 that are not present in any of the other arrays.

Example

Try out following example:
<?php
$array1 = array('blue'  => 1, 'red'  => 2, 'purple' => 3);

$array2 = array('blue' => 4, 'yellow' => 5, 'cyan'  => 6);

var_dump(array_diff($input_array1, $input_array2));
?> 
This will produce following result:
array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(3)
}

PHP Function array_diff_assoc()

Syntax

array array_diff_assoc( array $array1, array $array2 [, array $array3...] );

Definition and Usage

Compares array1 against array2 and returns the difference. Unlike array_diff() the array keys are used in the comparision.

Paramters

ParameterDescription
array1Required. The array to compare from
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array

Return Values

Returns an array containing all the values from array1 that are not present in any of the other arrays with the same keys.

Example

Try out following example:
<?php
$input_array1 = array( a=>"orange", b=>"mango", c=>"banana");
$input_array2 = array( a=>"orange", b=>"apple", c=>"banana");
print_r(array_diff_assoc($input_array1, $input_array2));

$input_array1 = array( a=>"orange", b=>mango", c=>"banana");
$input_array2 = array( a=>"banana", b=>"apple", c=>"orange");
print_r(array_diff_assoc($input_array1, $input_array2));
?> 
This will produce following result:
Array ( [b] => mango )
Array ( [a] => orange [b] => mango [c] => banana )

PHP Function array_diff()

Syntax

array array_diff ( array $array1, array $array2 [, array $array3 ...] );

Definition and Usage

Compares array1 against array2 and returns the difference.

Paramters

ParameterDescription
array1Required. The first array is the array that the others will be compared with.
array2Required. An array to be compared with the first array
array3Optional. An array to be compared with the first array

Return Values

Returns an array containing the differennces.

Example

Try out following example:
<?php
$input_array1 = array("orange", "banana", "apple");
$input_array2 = array("orange", "mango", "apple");
print_r(array_diff($input_array1, $input_array2));
?> 
This will produce following result:
Array ( [1] => banana )

PHP Function array_count_values()

Syntax

array array_count_values ( array $input );

Definition and Usage

Returns an array using the values of the input array as keys and their frequency in input as values.

Paramters

ParameterDescription
inputThe array of values to count

Return Values

Returns an assosiative array of values from input as keys and their count as value.

Example

Try out following example:
<?php
$input_array = array("orange", "mango", "banan", "orange" );
print_r(array_count_values($input_array));
?> 
This will produce following result:
Array ( [orange] => 2 [mango] => 1 [banana => 1 )

PHP Function array_combine()

Syntax

array array_combine ( array $keys, array $values );

Definition and Usage

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

Paramters

ParameterDescription
keysArray of keys to be used
valuesArray of values to be used

Return Values

Returns the combined array, FALSE if the number of elements for each array isn't equal or if the arrays are empty.

Example

Try out following example:
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?> 
This will produce following result:
Array([green] => avocado [red] => apple [yellow] => banana)

PHP Function array_chunk()

Syntax

array array_chunk ( array $input, int $size [, bool $preserve_keys] );

Definition and Usage

Chunks an array into size large chunks. The last chunk may contain less than size elements.

Paramters

ParameterDescription
inputThe array to work on
sizeThe size of each chunk
preserve_keysWhen set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing size elements.

Example

Try out following example:
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?> 
This will produce following result:
Array (
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

PHP Function array_change_key_case()

Syntax

array array_change_key_case ( array $input [, int $case] )

Definition and Usage

Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.

Paramters

ParameterDescription
inputThe array to work on
caseEither CASE_UPPER or CASE_LOWER (default)

Return Values

Returns an array with its keys lower or uppercased, or false if input is not an array.

Example

Try out following example:
<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?> 
This will produce following result:
Array ( [FIRST] => 1 [SECOND] => 4 )

PHP Function array()

Syntax

array(key1 => value1, key2 => value2...)

Definition and Usage

Returns an array of the parameters. The parameters can be given an index with the => operator

Paramters

ParameterDescription
keyOptional. Specifies the key, of type numeric or string. If not set, an integer key is generated, starting at 0
valueRequired. Specifies the value

Return Values

Returns an array of the parameters.

Example

Try out following example
<?php
$a=array("a"=>"Dog", "b"=>"Cat", "c"=>"Horse");
print_r($a);
?> 
This will produce following result:
Array ( [a] => Dog [b] => Cat [c] => Horse )
The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays.
<?php

$fruits = array (
    "fruits" => array("a"=>orange", "b"=>banana", "c"=>apple"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes" => array("first", 5 => "second", "third")
);
?> 

PHP for PERL Developers

This chapter will list out major similarities and differences in between PHP and PERL. This will help PERL developers to understand PHP very quickly and avoid common mistakes.

Similarities:

  • Compiled scripting languages: Both Perl and PHP are scripting languages.This means that they are not used to produce native standalone executables in advance of execution.
  • Syntax: PHP's basic syntax is very close to Perl's, and both share a lot of syntactic features with C. Code is insensitive to whitespace, statements are terminated by semicolons, and curly braces organize multiple statements into a single block. Function calls start with the name of the function, followed by the actual arguments enclosed in parentheses and separated by commas.
  • Dollar-sign variables: All variables in PHP look like scalar variables in Perl: a name with a dollar sign ($) in front of it.
  • No declaration of variables: As in Perl, you don.t need to declare the type of a PHP variable before using it.
  • Loose typing of variables: As in Perl, variables in PHP have no intrinsic type other than the value they currently hold. You can store iether number or string in same type of variable.
  • Strings and variable interpolation: Both PHP and Perl do more interpretation of double-quoted strings ("string") than of singlequoted strings ('string').

Differences:

  • PHP is HTML-embedded: Although it is possible to use PHP for arbitrary tasks by running it from the command line, it is more typically connected to a Web server and used for producing Web pages. If you are used to writing CGI scripts in Perl, the main difference in PHP is that you no longer need to explicitly print large blocks of static HTML using print or heredoc statements and instead can simply write the HTML itself outside of the PHP code block.
  • No @ or % variables: PHP has one only kind of variable, which starts with a dollar sign ($). Any of the datatypes in the language can be stored in such variables, whether scalar or compound.
  • Arrays versus hashes: PHP has a single datatype called an array that plays the role of both hashes and arrays/lists in Perl.
  • Specifying arguments to functions: Function calls in PHP look pretty much like subroutine calls in Perl. Function definitions in PHP, on the other hand, typically require some kind of list of formal arguments as in C or Java which is not the csse in PERL.
  • Variable scoping in functions: In Perl, the default scope for variables is global. This means that top-level variables are visible inside subroutines. Often, this leads to promiscuous use of globals across functions. In PHP, the scope of variables within function definitions is local by default.
  • No module system as such: In PHP there is no real distinction between normal code files and code files used as imported libraries.
  • Break and continue rather than next and last: PHP is more like C langauge and uses break and continue instead of next and last statement.
  • No elsif: A minor spelling difference: Perl's elsif is PHP's elseif.
  • More kinds of comments: In addition to Perl-style (#) single-line comments, PHP offers C-style multiline comments (/* comment */ ) and Java-style single-line comments (// comment).
  • Regular expressions: PHP does not have a built-in syntax specific to regular expressions, but has most of the same functionality in its "Perl-compatible" regular expression functions.

PHP for C Developers

The simplest way to think of PHP is as interpreted C that you can embed in HTML documents. The language itself is a lot like C, except with untyped variables, a whole lot of Web-specific libraries built in, and everything hooked up directly to your favorite Web server.
The syntax of statements and function definitions should be familiar, except that variables are always preceded by $, and functions do not require separate prototypes.
Here we will put some similarities and diferences in PHP and C

Similarities:

  • Syntax: Broadly speaking, PHP syntax is the same as in C: Code is blank insensitive, statements are terminated with semicolons, function calls have the same structure (my_function(expression1, expression2)), and curly braces ({ and }) make statements into blocks. PHP supports C and C++-style comments (/* */ as well as //), and also Perl and shell-script style (#).
  • Operators: The assignment operators (=, +=, *=, and so on), the Boolean operators (&&, ||, !), the comparison operators (<,>, <=, >=, ==, !=), and the basic arithmetic operators (+, -, *, /, %) all behave in PHP as they do in C.
  • Control structures: The basic control structures (if, switch, while, for) behave as they do in C, including supporting break and continue. One notable difference is that switch in PHP can accept strings as case identifiers.
  • Function names: As you peruse the documentation, you.ll see many function names that seem identical to C functions.

Differences:

  • Dollar signs: All variables are denoted with a leading $. Variables do not need to be declared in advance of assignment, and they have no intrinsic type.
  • Types: PHP has only two numerical types: integer (corresponding to a long in C) and double (corresponding to a double in C). Strings are of arbitrary length. There is no separate character type.
  • Type conversion: Types are not checked at compile time, and type errors do not typically occur at runtime either. Instead, variables and values are automatically converted across types as needed.
  • Arrays: Arrays have a syntax superficially similar to C's array syntax, but they are implemented completely differently. They are actually associative arrays or hashes, and the index can be either a number or a string. They do not need to be declared or allocated in advance.
  • No structure type: There is no struct in PHP, partly because the array and object types together make it unnecessary. The elements of a PHP array need not be of a consistent type.
  • No pointers: There are no pointers available in PHP, although the typeless variables play a similar role. PHP does support variable references. You can also emulate function pointers to some extent, in that function names can be stored in variables and called by using the variable rather than a literal name.
  • No prototypes: Functions do not need to be declared before their implementation is defined, as long as the function definition can be found somewhere in the current code file or included files.
  • Memory management: The PHP engine is effectively a garbage-collected environment (reference-counted), and in small scripts there is no need to do any deallocation. You should freely allocate new structures - such as new strings and object instances. IN PHP5, it is possible to define destructors for objects, but there is no free or delete. Destructors are called when the last reference to an object goes away, before the memory is reclaimed.
  • Compilation and linking: There is no separate compilation step for PHP scripts.
  • Permissiveness: As a general matter, PHP is more forgiving than C (especially in its type system) and so will let you get away with new kinds of mistakes. Unexpected results are more common than errors.

Object Oriented Programming in PHP

We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects.

Object Oriented Concepts:

Before we go in detail, lets define important terms related to Object Oriented Programming.
  • Class: This is a programmer-defined datatype, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
  • Object: An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
  • Member Variable: These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.
  • Member function: These are the function defined inside a class and are used to access object data.
  • Inheritance: When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
  • Parent class: A class that is inherited from by another class. This is also called a base class or super class.
  • Child Class: A class that inherits from another class. This is also called a subclass or derived class.
  • Polymorphism: This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
  • Overloading: a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.
  • Data Abstraction: Any representation of data in which the implementation details are hidden (abstracted).
  • Encapsulation: refers to a concept where we encapsulate all the data and member functions together to form an object.
  • Constructor: refers to a special type of function which will be called automatically whenever there is an object formation from a class.
  • Destructors: refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.

Defining PHP Classes:

The general form for defining a new class in PHP is as follows:
<?php
class phpClass{
   var $var1;
   var $var2 = "constant string";
   function myfunc ($arg1, $arg2) {
      [..]
   }
   [..]
}
?>
Here is the description of each line:
  • The special form class, followed by the name of the class that you want to define.
  • A set of braces enclosing any number of variable declarations and function definitions.
  • Variable declarations start with the special form var, which is followed by a conventional $ variable name; they may also have an initial assignment to a constant value.
  • Function definitions look much like standalone PHP functions but are local to the class and will be used to set and access object data.

Example:

Here is an example which defines a class of Books type:
<?php
class  Books{
    /* Member variables */
    var $price;
    var $title;
    /* Member functions */
    function setPrice($par){
       $this->$price = $var;
    }
    function getPrice(){
       echo $this->$price ."<br/>";
    }
    function setTitle($par){
       $this->$title = $par;
    }
    function getTitle(){
       echo $this->$title ." <br/>";
    }
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP

Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator.
   $physics = new Books;
   $maths = new Books;
   $chemistry = new Books;
Here we have created three objects and these objects are independent of each other and they will have their existance separately. Next we will see how to access member function and process member variables.

Calling Member Functions

After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only.
Following example shows how to set title and prices for the three books by calling member functions.
   $physics->setTitle( "Physics for High School" );
   $chemistry->setTitle( "Advanced Chemistry" );
   $maths->setTitle( "Algebra" );

   $physics->setPrice( 10 );
   $chemistry->setPrice( 15 );
   $maths->setPrice( 7 );
Now you call another member functions to get the values set by in above example:
   $physics->getTitle();
   $chemistry->getTitle();
   $maths->getTitle();
   $physics->getPrice();
   $chemistry->getPrice();
   $maths->getPrice();
This will produce follwoing result:
  Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Constructor Functions:

Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions.
PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function.
Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.
function __construct( $par1, $par2 ){
   $price = $par1;
   $title = $par2;
}
Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below:
   $physics = new Books( "Physics for High School", 10 );
   $maths = new Books ( "Advanced Chemistry", 15 );
   $chemistry = new Books ("Algebra", 7 );

   /* Get those set values */
   $physics->getTitle();
   $chemistry->getTitle();
   $maths->getTitle();

   $physics->getPrice();
   $chemistry->getPrice();
   $maths->getPrice();
This will produce following result:
  Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Destructor:

Like a constructor function you can define a destructor function using function __destruct(). You can release all the resourceses with-in a destructor.

Inheritance:

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows:
  class Child extends Parent {
     <definition body>
  }
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics:
  • Automatically has all the member variable declarations of the parent class.
  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.
Following example inherit Books class and adds more functionality based on the requirement.
class Novel extends Books{
   var publisher;
   function setPublisher($par){
     $this->$publisher = $par;
   }
   function getPublisher(){
     echo $this->$publisher. "<br />";
   }
}
Now apart from inherited functions, class Novel keeps two additional member functions.

Function Overriding:

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.
In the follwoing example getPrice and getTitle functions are overriden to retrun some values.
    function getPrice(){
       echo $this->$price . "<br/>";
       return $this->$price;
    }
    function getTitle(){
       echo $this->$title . "<br/>";
       return $title;
    }

Public Members:

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations:
  • From outside the class in which it is declared
  • From within the class in which it is declared
  • From within another class that implements the class in which it is declared
Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected.

Private members:

By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.
A class member can be made private by using private keyword infront of the member.
class MyClass {
   private $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   function myPublicFunction() {
      return("I'm visible!");
   }
   private function myPrivateFunction() {
      return("I'm  not visible outside!");
   }
}
When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members:

A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword infront of the member.
Here is different version of MyClass:
class MyClass {
   protected $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   function myPublicFunction() {
      return("I'm visible!");
   }
   protected function myPrivateFunction() {
      return("I'm  visible in child class!");
   }
}

Interfaces:

Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to theri requirements. You can say, interfaces are skeltons which are implemented by developers.
As of PHP5, it is possible to define an interface, like this:
interface Mail {
   public function sendMail();
}
Then, if another class implemented that interface, like this:
class Report implements Mail {
   // sendMail() Definition goes here
}

Constants:

A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable. Once you declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of MyClass:
class MyClass {
   const requiredMargin = 1.7;
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}
In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do.

Abstract Classes:

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this:
When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibillity.
abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}
Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class.

Static Keyword:

Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).
Try out following example:
<?php
class Foo
{
    public static $my_static = 'foo';

    public function staticValue() {
        return self::$my_static;
    }
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";

Final Keyword:

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php
class BaseClass {
   public function test() {
       echo "BaseClass::test() called<br>";
   }
  
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called<br>";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called<br>";
   }
}
?>

Calling parent constructors:

Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here's a simple example:
class Name
{
   var $_firstName;
   var $_lastName;
   function Name($first_name, $last_name)
   {
     $this->_firstName = $first_name;
     $this->_lastName = $last_name;
   }
   function toString() {
     return($this->_lastName .", " .$this->_firstName);
   }
}
class NameSub1 extends Name
{
   var $_middleInitial;
   function NameSub1($first_name, $middle_initial, $last_name) {
       Name::Name($first_name, $last_name);
       $this->_middleInitial = $middle_initial;
   }
   function toString() {
       return(Name::toString() . " " . $this->_middleInitial);
   }
}
In this example, we have a parent class (Name), which has a two-argument constructor, and a subclass (NameSub1), which has a three-argument constructor. The constructor of NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing two of its arguments along) and then setting an additional field. Similarly, NameSub1 defines its nonconstructor toString() function in terms of the parent function that it overrides.
NOTE: A constructor can be defined with the same name as the name of a class. It is defined in above example.

PHP and XML

XML is a markup language that looks a lot like HTML. An XML document is plain text and contains tags delimited by < and >.There are two big differences between XML and HTML:
  • XML doesn't define a specific set of tags you must use.
  • XML is extremely picky about document structure.
XML gives you a lot more freedom than HTML. HTML has a certain set of tags: the <a></a> tags surround a link, the <p> startsa paragraph and so on. An XML document, however, can use any tags you want. Put <rating></rating> tags around a movie rating, >height></height> tags around someone's height. Thus XML gives you option to device your own tags.
XML is very strict when it comes to document structure. HTML lets you play fast and loose with some opening and closing tags. BUt this is not the case with XML.

HTML list that's not valid XML:

<ul>
<li>Braised Sea Cucumber
<li>Baked Giblets with Salt
<li>Abalone with Marrow and Duck Feet
</ul>
This is not a valid XML document because there are no closing </li> tags to match up with the three opening <li> tags. Every opened tag in an XML document must be closed.

HTML list that is valid XML:

<ul>
<li>Braised Sea Cucumber</li>
<li>Baked Giblets with Salt</li>
<li>Abalone with Marrow and Duck Feet</li>
</ul>

Parsing an XML Document:

PHP 5's new SimpleXML module makes parsing an XML document, well, simple. It turns an XML document into an object that provides structured access to the XML.
To create a SimpleXML object from an XML document stored in a string, pass the string to simplexml_load_string( ). It returns a SimpleXML object.

Example:

Try out following example:
<?php

$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;

$xml = simplexml_load_string($channel);
print "The $xml->title channel is available at $xml->link. ";
print "The description is \"$xml->description\"";
?>
It will produce following result:
The What's For Dinner channel is available at http://menu.example.com/. The description is "Choose what to eat tonight."

Generating an XML Document:

SimpleXML is good for parsing existing XML documents, but you can't use it to create a new one from scratch.
The easiest way to generate an XML document is to build a PHP array whose structure mirrors that of the XML document and then to iterate through the array, printing each element with appropriate formatting.

Example:

Try out following example:
<?php

$channel = array('title' => "What's For Dinner",
                 'link' => 'http://menu.example.com/',
                 'description' => 'Choose what to eat tonight.');
print "<channel>\n";
foreach ($channel as $element => $content) {
   print " <$element>";
   print htmlentities($content);
   print "</$element>\n";
}
print "</channel>";
?>
It will produce following result:
<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/</link>
<description>Choose what to eat tonight.</description>
</channel></html>

PHP and AJAX

What is AJAX ?

  • AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
  • Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
  • With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

PHP and AJAX Example:

To clearly illustrate how easy it is to access information from a database using Ajax and PHP, we are going to build MySQL queries on the fly and display the results on "ajax.html". But before we proceed, lets do ground work. Create a table using the following command.
NOTE: We are asuing you have sufficient privilege to perform following MySQL operations
CREATE TABLE `ajax_example` (
  `name` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `sex` varchar(1) NOT NULL,
  `wpm` int(11) NOT NULL,
  PRIMARY KEY  (`name`)
) 
Now dump the following data into this table using the foloowing SQL statements
INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);

Client Side HTML file

Now lets have our client side HTML file which is ajax.html and it will have following code
<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!
 
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.value = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "?age=" + age ;
 queryString +=  "&wpm=" + wpm + "&sex=" + sex;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' 
                              value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
NOTE: The way of passing variables in the Query is according to HTTP standard and the have formA
URL?variable1=value1;&variable2=value2;
Now the above code will give you a screen as given below

NOTE: This is dummy screen and would not work
Max Age: 

Max WPM:

Sex:
Your result will display here

Server Side PHP file

So now your client side script is ready. Now we have to write our server side script which will fetch age, wpm and sex from the database and will send it back to the client. Put the following code into "ajax-example.php" file
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
 //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
 //Select Database
mysql_select_db($dbname) or die(mysql_error());
 // Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
 // Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
 //build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
 $query .= " AND age <= $age";
if(is_numeric($wpm))
 $query .= " AND wpm <= $wpm";
 //Execute query
$qry_result = mysql_query($query) or die(mysql_error());

 //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
 $display_string .= "<tr>";
 $display_string .= "<td>$row[name]</td>";
 $display_string .= "<td>$row[age]</td>";
 $display_string .= "<td>$row[sex]</td>";
 $display_string .= "<td>$row[wpm]</td>";
 $display_string .= "</tr>";
 
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

Now try by entering a valid value in "Max Age" or any other box and then click Query MySQL button.
Max Age: 

Max WPM:

Sex:
Your result will display here

If you have successfully completed this lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.

PHP Date and Time

Dates are so much part of everyday life that it becomes easy to work with them without thinking. PHP also provides powerful tools for date arithmetic that make manipulating dates easy.

Getting the Time Stamp with time():

PHP's time() function gives you all the information that you need about the current date and time. It requires no arguments but returns an integer.
The integer returned by time() represents the number of seconds elapsed since midnight GMT on January 1, 1970. This moment is known as the UNIX epoch, and the number of seconds that have elapsed since then is referred to as a time stamp.
<?php
print time();
?>
It will produce following result:
948316201
This is something difficult to understand. But PHP offers excellent tools to convert a time stamp into a form that humans are comfortable with.

Converting a Time Stamp with getdate():

The function getdate() optionally accepts a time stamp and returns an associative array containing information about the date. If you omit the time stamp, it works with the current time stamp as returned by time().
Following table lists the elements contained in the array returned by getdate().
KeyDescriptionExample
secondsSeconds past the minutes (0-59)20
minutesMinutes past the hour (0 - 59)29
hoursHours of the day (0 - 23)22
mdayDay of the month (1 - 31)11
wdayDay of the week (0 - 6)4
monMonth of the year (1 - 12)7
yearYear (4 digits)1997
ydayDay of year ( 0 - 365 )19
weekdayDay of the weekThursday
monthMonth of the yearJanuary
0Timestamp948370048
Now you have complete control over date and time. You can format this date and time in whatever format you wan.

Example:

Try out following example
<?php
$date_array = getdate();
foreach ( $date_array as $key => $val )
{
   print "$key = $val<br />";
}
$formated_date  = "Today's date: ";
$formated_date .= $date_array[mday] . "/";
$formated_date .= $date_array[mon] . "/";
$formated_date .= $date_array[year];

print $formated_date;
?>
It will produce following result:
seconds = 27
minutes = 25
hours = 11
mday = 12
wday = 6
mon = 5
year = 2007
yday = 131
weekday = Saturday
month = May
0 = 1178994327
Today's date: 12/5/2007

Converting a Time Stamp with date():

The date() function returns a formatted string representing a date. You can exercise an enormous amount of control over the format that date() returns with a string argument that you must pass to it.
date(format,timestamp)
The date() optionally accepts a time stamp if ommited then current date and time will be used. Any other data you include in the format string passed to date() will be included in the return value.
Following table lists the codes that a format string can contain:
FormatDescriptionExample
a'am' or 'pm' lowercasepm
A'AM' or 'PM' uppercasePM
dDay of month, a number with leading zeroes20
DDay of week (three letters)Thu
FMonth nameJanuary
hHour (12-hour format - leading zeroes)12
HHour (24-hour format - leading zeroes)22
gHour (12-hour format - no leading zeroes)12
GHour (24-hour format - no leading zeroes)22
iMinutes ( 0 - 59 )23
jDay of the month (no leading zeroes20
l (Lower 'L')Day of the weekThursday
LLeap year ('1' for yes, '0' for no)1
mMonth of year (number - leading zeroes)1
MMonth of year (three letters)Jan
rThe RFC 2822 formatted dateThu, 21 Dec 2000 16:01:07 +0200
nMonth of year (number - no leading zeroes)2
sSeconds of hour20
UTime stamp948372444
yYear (two digits)06
YYear (four digits)2006
zDay of year (0 - 365)206
ZOffset in seconds from GMT+5

Example:

Try out following example
<?php
print date("m/d/y G.i:s<br>", time());
print "Today is ";
print date("j of F Y, \a\\t g.i a", time());
?>
It will produce following result:
01/20/00 13.27:55
Today is 20 of January 2000, at 1.27 pm
Hope you have good understanding on how to format date and time according to your requirement.

Labels

AJAX (1) Answers (1) Apache (1) Array (16) bug (1) C (1) C++ (1) Calendar (1) Class (1) Commands (1) Cookies (2) Database (2) Date (7) Days (1) explode (1) File Upload (1) FILES (1) firewall (1) fix (1) Functions (26) GET (1) GMT (1) JavaScript (2) localhost (1) Mail (1) Menu (1) MYSQL (13) PERL (1) PHP (36) php.ini (1) POST (1) preg_match (1) Questions (1) Script (1) SMS (2) Solution (1) String (1) Time (5) Time Zone (1) Vista (1) Wamp Server (1) windows 7 (2) XML (1)

Popular Posts

Popular Posts