Pages

Thursday 10 April 2014

PHP functions defination with examples

Scope of the Variables
When a variable is declared in a function then it remains local to that function. This means that, that variable cannot be accessed from outside the function or by other functions. It is helpful when two variables of same name have been declared in different functions. This prevents you from accidentally overwriting the contents of a variable.
In the following example you will see how a variable defined in a function cannot be accessed from outside the function.
 
Example
 
<html>
<body>
 
<?php
function abc()
{
$a = "Testing this variable";
}
echo "Lets test it: $a <br/>";
?>
 
</body>
</html>
Output
The Global Statement
The global statement comes in handy when you want to access variables that are declared outside the function. In this if a variable is declared and assigned a value outside a function, and then we declare a global variable of the same name in the function, then that function can access the variable that has been declared outside the function.
In the following example we will show how a global variable declared inside a function can access the variable declared outside the function.
 
Example:
 
<html>
<body>
 
<?php
$a = "Hello how are you";
function abc()
{
global $a;
echo $a;
}
abc();
?>
 
</body>
</html>
Output
 
The Static Keyword
The static keyword is used when declaring variables in functions. The purpose of the static variable is to inform PHP that this variable should not be destroyed when the given function executes. Instead of destroying that variable, the value of that variable is saved for the next time needed.
The static variable is used to retain certain variables within the function for the life of the execution of the script.
Syntax
Static $variable [= initial value];
In the following example we will be using the static variable in the function to see that how many times a given function has been called.
Example
<html>
<body>
 
<?php
function func()
{
static $a = 0;
$a++;
echo "This function has executed $a time(s).<br/>";
}

for($i=0; $i<8; $i++)
{
func();
}
?>
 
</body>
</html>
 
 
 
Output:

Classes and Objects in php with examples

What is a Class?
The Class in PHP is basically the same as in other languages such as Java. The class definition begins with the keyword class, followed by a class name. The form name can be any name except a reserved word or keyword in PHP. The class name is followed by a pair of curly braces which contain the definition of class members and methods.
 
Example of a Class
 
<?php
 
Class abc
{
//member functions and variables go here
}
 
?>
What is an Object?
An Object is an enclosed bundle of variables and functions which is copied from a Class. Objects provide an easy interface and hide a lot of their inner workings. The object sends orders through special functions called methods and they can return information.
While creating a Class, a set of characteristics is laid down. By creating Objects of that type, entities are created that share these characteristics but the Object might initialize them as different values.
Example
 
Suppose there is a class named building. This class would have a characteristic named floor. All the objects of class building would share the characteristics of floor, but some would initialize it to “one”, some to “two”, others to “three” or “four”, and so on.
The benefit of object oriented code is that it is re-useable. In this the classes can be used to create different objects and classes from one project can be used in other projects as well. Child classes can also be created which inherits the properties of the parent classes.
Creating an Instance
To start with, a class having no member functions and variables is not useful. For a class to be completely useful, member functions and variables have to be added in that class.
Let’s take an example of a class with a variable in it.
 
Example
 
<?php
 
Class abc
{
$a = “Hello!”;
}
 
?>
The class abc is the basis from which many objects can be instantiated. The new keyword is used to create an object. Now any abc object that is created contains a property called $a with the value of “Hello”. This property can be accessed and even be changed with the help of objects.
In this the -> operator is used to access or change the properties of the object.
In the following example $obj1 and $obj2 are the objects of the class abc. In this $obj2 has been assigned the string “Welcome to expertrating!” to its $a property.
Example
 
<html>
<body>
 
<?php
 
Class abc
{
var $a = "Hello";
}
 
$obj1 = new abc();
$obj2 = new abc();
$obj2->a = "Welcome to expertrating!";
echo "$obj1->a<br />";
echo "$obj2->a<br />";
 
?>
 
</body>
</html>
Output
Extends
Another feature of object oriented programming is used in PHP, which is inheritance. In PHP a class a class can inherit methods, functions and members of other class by using the extends keyword in the declaration. In PHP it is not possible to inherit from multiple classes, a class can inherit from only one base class.
The class from which inheritance is done is called the parent class or base class and the class which inherits is called the child class.
The Keyword Final
The final keyword prevents the child classes from overriding a method. This can be done by prefixing the method with the keyword final. If the complete class is being defined as final then that class cannot be extended.
 
Example
 
final class test
{
//methods and functions
}
The class defined above i.e. class test cannot be overloaded as it has been finalized by using the keyword final with it.
Abstract
A new concept of abstract classes and methods has been introduced in PHP5. When a class is defined as abstract then it is not allowed to create the instance of that class. A class that contains at least one abstract method must also be abstract. The methods defined as abstract cannot define the implementation; they just declare the method’s signature.
When a child class is inheriting from an abstract parent class, then all the methods marked abstract in parent class declaration must also be additionally defined by the child class. These methods must be defined with the same or weaker access. This means that if an abstract method is declared as protected in the parent class then it must be declared either as protected or public in the child class.
Static Keyword
When class members or methods are declared as static then there is no need to instantiate that class. These members and methods are accessible without the instantiation of the class. If a member is declared as static then it cannot be accessed by an instantiated class object, but a method declared as static can be accessed by an instantiated class object.
The static declaration of a class must be after the visibility declaration (means that after the member or method has been declared as public, protected, or private).
The static method calls are resolved at compile time and static properties cannot be accessed through the object through the arrow operator (->).
Interfaces
Object interfaces allow the creation of a code which specifies that which method a class must implement, without having to define how these methods have to be handled.
Interfaces are defined in the same way as a class is defined. These interfaces are defined with the keyword “interface”. In the interface the contents of the methods do not have to be defined and all the methods declared in the interface must be declared as public.
Implementation of Interfaces
To implement an interface, the implements operator is used. The methods must be defined before implementation and all the methods in the interface must be implemented within a class.
Exceptions
Exception handling in PHP is similar to that of other programming languages. Within a PHP block of code we can throw, try and catch an exception. There must be at least one catch block in a try block. In this multiple catch blocks can be used to catch different class types. In exception handling the execution will continue after the last catch block has been encountered and exceptions can be thrown within catch blocks.
In exception handling when an exception is thrown, the code following the statement will not be executed rather PHP will attempt to find the first matching catch block. If the exception is not caught then it will result in a fatal error with an uncaught exception message.

PHP Advanced Topics with examples

Superglobals
In the previous chapters the concept of global variable was explained. A global variable is a variable declared at the top of the script outside the function. This variable is available to the complete script. Superglobal variables are arrays built into PHP. These superglobal variables are populated automatically with useful elements, and they are available in any scope. A superglobal array can be accessed within a function or a method without using the global keyword.
PHP Superglobals
  • $_COOKIE – It contains values provided to the script via HTTP cookies.

  • $_GET – It contains variables submitted to the script using HTTP get method.

  • $_POST – It contains variables submitted to the script using HTTP post method.

  • $_REQUEST – It is a combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays.

  • $_ENV – It contains keys and values set by the script’s shell.

  • $_FILES – It contains information about uploaded files.

  • $_SERVER – It contains variables made available by the server.

  • $GLOBALS – It contains all the global variables associated with the current script.
Instanceof Operator
The instanceof operator in PHP is used to determine whether a given object, the parents of that object, or its implemented interfaces are of a specified object class.
Example
<?php
class X { }
class Y { }
$thing = new X;
if ($thing instanceof X) {
echo 'X';
}
if ($thing instanceof Y) {
echo 'Y';
}
?>
 
Declare
The declare statement is used to set execution directives for a block of code. The syntax of the declare statement is similar to the syntax of other flow control statements.
Syntax
declare (directive)
statement
 
The directive section allows the behavior of the declare block to be set. In this only one directive is recognized, which is the ticks directive.
[ Ticks - A tick is an event that occurs for every N low level statements, which are executed within the declare block. The value of N is specified using the statement ticks = N in the directive section.]
The statement part of the declare block will be executed according to the directives set in the directive block.
Example
<?php
// how to use declare:
// the first way:
declare(ticks=1) {
// entire script here
}
// the second way:
declare(ticks=1);
// entire script here
?>

Php Advanced Class Concepts with example

Constructor
In PHP 5 developers can declare constructor methods for classes. In this, those classes which have a constructor method call this method for each newly created object. So, it is suitable for any initialization that the object may need before it is used. In this the parent constructors are not called implicitly if the child class defines a constructor.
Example
<?php

class ParentClass {
function __construct() {
print "In ParentClass constructor\n";
}
}
class ChildClass extends ParentClass {
function __construct() {
parent::__construct();
print "In ChildClass constructor\n";
}
}
$obj = new ParentClass();
$obj = new ChildClass();
?>
 

Destructors
The destructor concept is introduced in PHP 5. This destructor concept is similar to other object oriented languages. In this the destructor will be called as soon as all references to a particular object have been removed or when the object has been explicitly destroyed.
Example
<?php
class MyClass {
function __construct() {
print "In constructor\n";
$this->name = "MyClass";
}
function __destruct() {
print "Destroying " . $this->name . "\n";
}
}
$obj = new MyClass();
?>
 
Patterns
Patterns are ways to describe best practices and good designs. The patterns show a flexible solution to common programming problems.
Factory Pattern
In the factory pattern the objects are instantiated at runtime. It is called a factory pattern since it is responsible for manufacturing an object. A parameterized factory receives the name of the class to instantiate as argument.
Example
<?php
class Welcome
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
?>

Object Oriented Concepts with examples

  • 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 = $par;
    }
    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 ){
   $this->price = $par1;
   $this->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 $this->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.

Best PHP - Error Handling with example

When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.

This tutorial contains some of the most common error checking methods in PHP.
We will show different error handling methods:
  • Simple "die()" statements
  • Custom errors and error triggers
  • Error reporting

Basic Error Handling: Using the die() function

The first example shows a simple script that opens a text file:
<?php
$file=fopen("welcome.txt","r");
?>
If the file does not exist you might get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\webfolder\test.php on line 2
To prevent the user from getting an error message like the one above, we test whether the file exist before we try to access it:
<?php
if(!file_exists("welcome.txt"))
  {
  die("File not found");
  }
else
  {
  $file=fopen("welcome.txt","r");
  }
?>
Now if the file does not exist you get an error like this:
File not found
The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.
However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.

Creating a Custom Error Handler

Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.
This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context):

Syntax

error_function(error_level,error_message,
error_file,error_line,error_context)

ParameterDescription
error_levelRequired. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels
error_messageRequired. Specifies the error message for the user-defined error
error_fileOptional. Specifies the filename in which the error occurred
error_lineOptional. Specifies the line number in which the error occurred
error_contextOptional. Specifies an array containing every variable, and their values, in use when the error occurred

Error Report levels

These error report levels are the different types of error the user-defined error handler can be used for:
ValueConstantDescription
2E_WARNINGNon-fatal run-time errors. Execution of the script is not halted
8E_NOTICERun-time notices. The script found something that might be an error, but could also happen when running a script normally
256E_USER_ERRORFatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512E_USER_WARNINGNon-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024E_USER_NOTICEUser-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096E_RECOVERABLE_ERRORCatchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191E_ALLAll errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)
Now lets create a function to handle errors:
function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Ending Script";
  die();
  }
The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.
Now that we have created an error handling function we need to decide when it should be triggered.

Set Error Handler

The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script.
It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our custom error handler for all errors:
set_error_handler("customError");
Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.

Example

Testing the error handler by trying to output variable that does not exist:
<?php
//error handler function
function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr";
  }

//set error handler
set_error_handler("customError");

//trigger error
echo($test);
?>
The output of the code above should be something like this:
Error: [8] Undefined variable: test


Trigger an Error

In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.

Example

In this example an error occurs if the "test" variable is bigger than "1":
<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>
The output of the code above should be something like this:
Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6
An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.
Possible error types:
  • E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
  • E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted
  • E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally

Example

In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script:
<?php
//error handler function
function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Ending Script";
  die();
  }

//set error handler
set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>1)
  {
  trigger_error("Value must be 1 or below",E_USER_WARNING);
  }
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Ending Script
Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.

Error Logging

By default, PHP sends an error log to the server's logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.
Sending error messages to yourself by e-mail can be a good way of getting notified of specific errors.

Send an Error Message by E-Mail

In the example below we will send an e-mail with an error message and end the script, if a specific error occurs:
<?php
//error handler function
function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Webmaster has been notified";
  error_log("Error: [$errno] $errstr",1,
  "someone@example.com","From: webmaster@example.com");
  }

//set error handler
set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>1)
  {
  trigger_error("Value must be 1 or below",E_USER_WARNING);
  }
?>
The output of the code above should be something like this:
Error: [512] Value must be 1 or below
Webmaster has been notified
And the mail received from the code above looks like this:
Error: [512] Value must be 1 or below
This should not be used with all errors. Regular errors should be logged on the server using the default PHP logging system.

PHP - Multidimensional Arrays Best example

A multidimensional array is an array containing one or more arrays.
In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on.

Example

In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array
  (
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
  );
The array above would look like this if written to the output:
Array
(
[Griffin] => Array
  (
  [0] => Peter
  [1] => Lois
  [2] => Megan
  )
[Quagmire] => Array
  (
  [0] => Glenn
  )
[Brown] => Array
  (
  [0] => Cleveland
  [1] => Loretta
  [2] => Junior
  )
)

Example 2

Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] .
" a part of the Griffin family?";
The code above will output:
Is Megan a part of the Griffin family?