PHP language cheat sheet 2

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

Features/Syntax Description/examples

Namespaces

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:
    <?php
    namespace myNamespace;
     ...
    ?>
    
    Or
    <?php
    namespace myLib\myNamespace;
     ....
    ?>
    
  2. Using namespaces:
    <?php
    $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:

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

Multiple namespaces:

<?php
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

file1.php

<?php
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__;
 }
}
file2.php
<?php
include "test1.php";
$a= new xyz\MyClass();
echo $a->aMethod().'<br>';
echo xyz\MyClass::aStaticMethod().'<br>';
echo xyz\MyConst.'<br>';
echo xyz\myFunction();
Output:
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):

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

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

sub namespace example:

subNamespace.php

<?php
namespace ns1\ns2;

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

parentNamespace.php

<?php
namespace ns1;
include 'subNamespace.php';

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

Exceptions

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

Catching exceptions

try{
  //code
}
catch(Exception $e){
  //handle exception
}
finally{
 //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.

<?php
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(),
                 '<br>';
} finally{
echo '<br>done';
}

Output:

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

done

Custom Exception

Custom Exception can be created by extending Exception class.

See also:

Predefined Exceptions

<?php
class MyException extends Exception {
	function __construct($msg){
		parent::__construct($msg);
	}
}

throw new MyException("my test exception");

Output

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.



Generator::send($value)

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.

<?php
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>';
}

Output

class: Generator
0=>orange
1=>apple
2=>banana

See Also: get_Class()

Yielding key values:

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

$var = items();
foreach ( $var as $key => $value ) {
 echo $key . '=>' . $value . '<br>';
}
0=>0
1=>2
2=>4

See Also: range() function

Generator::send($value) example:

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

$gen = listener();
$gen->send('msg1');
$gen->send('msg2');
listener starts
msg1
looping next
msg2
looping next

Yielding by Reference example:

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

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

HTTP GET/POST params

  • $_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:

    if ($_SERVER['REQUEST_METHOD']==='POST'){
    }
    elseif($_SERVER['REQUEST_METHOD']==='GET'){
    }
    ..
         

    Also see: HTTP Request Methods

<?php
print_r($_GET);
URL: http://localhost:8080/test.php?a=1&b=abc

Output

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

Post example:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  echo "Message received in post method: " . $_POST['msg'];
  exit();
}
?>
<html>
<body>

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

</body>
</html>

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

test1.php

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

test2.php

<?php
session_start();
echo '<h3>test2 page</h3>';
echo 'session array: <br>';
print_r($_SESSION);
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

page.html

<form enctype="multipart/form-data" action="upload.php" method="POST">
Send this file: <input name="selectedFile" type="file" />
<input type="submit" value="Send File" />
</form>
  
<?php
echo '$_FILES array:<br>';
print_r($_FILES);
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