PHP language cheat sheet 2

[Updated: May 25, 2017, Created: Oct 29, 2016]

Features/Syntax Description/examples


It's a way of encapsulating items and to avoid name collision of functions, classes and constants. Also good for organisation and ownership.

  1. Defining namespaces:
    namespace myNamespace;
    namespace myLib\myNamespace;
  2. Using namespaces:
    $var = new myLib\myNamespace\MyClass();
    Namespaces doesn't import external file code. We still need to add include/required statements for that.

    For dynamically class instantiation:

    $var = 'myLib\myNamespace\MyClass';
    $obj = new $var();

Multiple namespaces:

namespace MyNamespace{
namespace MyAnotherNamespace{
namespace{//unnamed, global code

we can skip curly brackets but that's not recommended.

No code may exist outside of the namespace brackets except for an opening declare statement.

Important features:

  • Namespace declarations cannot be nested.
  • Namespace declaration statement has to be the very first statement in the script.
  • The magic constant __NAMESPACE__ can be used to find current namespace.
  • Aliasing namespace:
    use xyz as abc;
    Using multiple namespaces:
    use B\D, C\E as F;
  • The 'namespace' keyword can be used to access an element from the current namespace:
    $var = new namespace\AClass().
  • To access global features in case of collision prepend with '\' e.g. \strlen().
  • sub namespacing: namespace A inside namespace X\Y resolves to X\Y\A


namespace xyz;

const MyConst = 'a constant value';
function myFunction() {
 echo 'in function ' . __FUNCTION__;
class MyClass {

 function aMethod() {
  return 'in class method ' .
          __CLASS__ . '#' . __METHOD__;
 static function aStaticMethod() {
  return 'in static method ' . __METHOD__;
include "test1.php";
$a= new xyz\MyClass();
echo $a->aMethod().'<br>';
echo xyz\MyClass::aStaticMethod().'<br>';
echo xyz\MyConst.'<br>';
echo xyz\myFunction();
in class method xyz\MyClass#xyz\MyClass::aMethod
in static method xyz\MyClass::aStaticMethod
a constant value
in function xyz\myFunction

Aliasing example (file3.php):

include "test1.php";
use xyz as abc;

$a= new abc\MyClass();
echo $a->aMethod();
in class method xyz\MyClass#xyz\MyClass::aMethod

sub namespace example:


namespace ns1\ns2;

function process() {
 	echo 'in: namespace:' . __NAMESPACE__ .
        ', function: ' . __FUNCTION__;


namespace ns1;
include 'subNamespace.php';

//using relative namespace
echo ns2\process();
run parentNamespace.php.
in: namespace:ns1\ns2, function: ns1\ns2\process


Just like C++, Java and other languages, php provides exception handling mechanism via try/catch/finally block and by throw statements:

Catching exceptions

catch(Exception $e){
  //handle exception
 //this will always get executed

Throwing exception

//on some error condition
throw new Exception('an exception message');

Exception is the base class for all exceptions.

function divide($number, $divisor) {
  if (! $divisor) {
    throw new Exception('The divisor is not a valid value');
  } else {
    echo $number / $divisor;

try {
 divide(30, 2);
 divide(3, 0);
} catch ( Exception $e ) {
 echo '<br>exception caught:', $e->getMessage(),
                '<br>',  $e->getTraceAsString(),
} finally{
echo '<br>done';


exception caught:The divisor is not a valid value
#0 D:\eclipse-workspace\Php2\exception.php(13): divide(3, 0) #1 {main}


Custom Exception

Custom Exception can be created by extending Exception class.

See also:

Predefined Exceptions

class MyException extends Exception {
	function __construct($msg){

throw new MyException("my test exception");


Fatal error: Uncaught exception 'MyException' with message 'my test exception' in D:\eclipse-workspace\Php2\exception2.php:8 Stack trace: #0 {main} thrown in D:\eclipse-workspace\Php2\exception2.php on line 8

Generator function

A function can be used to create an instance of Generator class. Generator class implements Iterator interface, that makes it candidate for foreach loop.

yield keyword

A generator function instead of returning a value uses yield keyword, one or more times to pass the a variable argument to foreach loop.

Each uses of yield waits for the caller to process the element.

Yielding key/value pair

Yielding a key/value pair inside generator function is similar to that used to define an associative array.

yield $key => $value;

Yielding values by reference

Generator function can yield values by reference. It is done by prepending & with the generator function and on caller.


This method sends value to the generator function.

In this scenario yield is assign to a variable inside generator function.

Each uses of yield keyword waits for the caller to send value.

function items() {
	$fruits = array("orange", "apple", "banana");
	foreach ( $fruits as $fruit ) {
		yield $fruit;

$var = items();
echo "class: ".get_class($var);
echo '<br>';
$var = items();
echo "class: " . get_class($var);
echo '<br>';
foreach ( $var as $key => $value ) {
  echo $key . '=>' . $value . '<br>';


class: Generator

See Also: get_Class()

Yielding key values:

function items() {
 foreach ( range(0,4,2) as $key =>$value) {
  yield $key => $value;

$var = items();
foreach ( $var as $key => $value ) {
 echo $key . '=>' . $value . '<br>';

See Also: range() function

Generator::send($value) example:

function listener() {
	echo __FUNCTION__ . " starts <br>";
	while ( true ) {
		$varReceived = yield ;
		echo $varReceived . '<br>';
		echo 'looping next<br>';
	echo 'function ends<br>';

$gen = listener();
listener starts
looping next
looping next

Yielding by Reference example:

function &genFunc() {
 $value = 'item1';
 echo $value . '<br>';
 yield $value;
 echo $value . '<br>';

$var = genFunc();
foreach ($var as &$value){
  $value .=' modified';
item1 modified


  • $_GET

    An associative array containing variables passed via HTTP GET method.

  • $_POST

    An associative array containing variables passed via HTTP POST method.

  • GET/POST checking:

    Use superglobal $_SERVER array:


    Also see: HTTP Request Methods

URL: http://localhost:8080/test.php?a=1&b=abc


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

Post example:

  echo "Message received in post method: " . $_POST['msg'];

<form action="<?php $_PHP_SELF ?>" method="POST">
 Message: <input type="text" name="msg" /> <input type="submit" />


URL: http://localhost:8080/test.php

Enter a message in text box and click on submit button:

HTTP Sessions

The superglobal variable $_SESSION contains all session variables/values.

To start a new session or resume existing session, we have to call session_start() method.

Also see:

Session functions
What is HTTP Session?
Session Configurations


echo '<h3>test1 page</h3>';
$_SESSION['page1Data'] = 'page1 data';
echo '<br><a href="test2.php">go to test2 page</a>';


echo '<h3>test2 page</h3>';
echo 'session array: <br>';
URL: http://localhost:8080/test1.php

Click on 'go to test2 page'

File uploads

$_FILES is an associative array of uploaded file information.

File uploaded in php is automatically saved to an O.S. temporary location.

In our application we can move the uploaded file form temp location to the application specific location by using move_uploaded_file() function.

We can also read the content of the file by using file_get_contents()

See also:

Handling file uploads


<form enctype="multipart/form-data" action="upload.php" method="POST">
Send this file: <input name="selectedFile" type="file" />
<input type="submit" value="Send File" />
echo '$_FILES array:<br>';
echo '<br><br>';

$uploadedFile = $_FILES["selectedFile"];
$pathToSave = "upload/" . $uploadedFile["name"];

if (move_uploaded_file($uploadedFile["tmp_name"],
		                                $pathToSave)) {
	echo "The uploaded file  " . $uploadedFile["name"] .
	      " has been saved to $pathToSave.<br>";
echo '<br>File contents:<br>';
echo file_get_contents($pathToSave);
URL: http://localhost:8080/page.html Click on 'Choose file' button, select the file and then click on 'Send File' button. (I selected a file test.txt which contains a single line: 'this is a test file'). The file 'upload/test.txt' will be saved at the same location of upload.php script.

See Also