Traits vs Interfaces

Interfaces : An interface defines a set of methods that the implementing class must implement.

Trait : When a trait is use’d the implementations of the methods come along too–which doesn’t happen in an Interface.

Late Static Binding in PHP

Basically, it boils down to the fact that the self keyword does not follow the rules of inheritance. self always resolves to the class in which it is used. This means that if you make a method in a parent class and call it from a child class, self will not reference the child as you might expect.

Late static binding introduces a new use for the static keyword, which addresses this particular shortcoming. When you use static, it represents the class where you first use it, ie. it ‘binds’ to the runtime class.

Overloading in PHP

Overloading has a different meaning in PHP. PHP does not support function overloading in the same manner as C++. However it possible to pass different number of arguments to a function using func_get_args.

function findSum() {
$sum = 0;
foreach (func_get_args() as $arg) {
$sum += $arg;
return $sum;

echo findSum(1, 2), '
'; //outputs 3
echo findSum(10, 2, 100), '
'; //outputs 112
echo findSum(10, 22, 0.5, 0.75, 12.50), '
'; //outputs 45.75

Overloading in PHP provides means to dynamically “create” properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.
The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope.
Example for property overloading: __set() and __get()
Example for method overloading: __call()


As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own.

trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }

class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */

class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */

mysqli (MySQL Improved)

The mysqli extension, or as it is sometimes known, the MySQL improved extension, was developed to take advantage of new features found in MySQL systems versions 4.1.3 and newer

The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:

– Object-oriented interface

– Support for Prepared Statements

– Support for Multiple Statements

– Support for Transactions

– Enhanced debugging capabilities

– Embedded server support

$mysqli = new mysqli("", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;

$res = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
if (!$res) {
die('There was an error running the query [' . $db->error . ']');
$row = $res->fetch_assoc();
echo $row['_msg'];

echo 'Total results: ' . $res->num_rows;

$statment = $db->prepare("SELECT `name` FROM `users` WHERE `username` = ? and `age` = ?");
$statement->bind_param('si', $name, $age);
$result = $statement->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){

In bind param, first parameter denotes the types “s for string, i for integer, d for decimal, etc)

PHP Data Objects & Prepared Statements

PDO provides a data-access abstraction layer, which means that, regardless of which database you’re using, you use the same functions to issue queries and fetch data.

try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "

// Persistent Connections

Prepared Statements :
They can be thought of as a kind of compiled template for the SQL that an application wants to run, that can be customized using variable parameters. Prepared statements offer two major benefits:
a) The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters.
b) The parameters to prepared statements don’t need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur

$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// insert one row
$name = 'one';
$value = 1;

// repeated inserts
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// fetching data
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {

PDO vs mysqli :
While PDO has its advantages, such as a clean, simple, portable API, its main disadvantage is that it doesn’t allow you to use all of the advanced features that are available in the latest versions of MySQL server. For example, PDO does not allow you to use MySQL’s support for Multiple Statements.

PDO works with several databases whereas MySQLi works with MySQL only.

PDO has named parameters whereas MySQLi does not.
$pdo->prepare(‘SELECT * FROM users WHERE username = :username AND email = :email’);
$params = array(‘:username’ => ‘test’, ‘:email’ => $mail);

$mysqli->prepare(‘SELECT * FROM users WHERE username = ? AND email = ?’);
$query->bind_param(‘test’, $mail);–net-24059

What is ob_start in php ?

The PHP output buffering will save all the server outputs ( html and php prints) to a string variable.

So to start buffering, use ob_start(); this will keep saved any output.
Then you use $variable = ob_get_clean(); to stop buffering, and copy the buffer content to the variable.

Here are few samples of the use of ob_start() and ob_get_clean()

ob_start(); //Turn on output buffering ?>
Hello world, link
$var = ob_get_clean(); ?>
//copy current buffer contents into $message variable and delete current output buffer

Explain PHP namespaces

Previously in PHP you can’t have two classes that share the same name. They have to be unique. The issue with this restriction is that if you are using a third party library which has a class named User, then you can’t create your own class also called User. This is a real shame, because that’s a pretty convenient class name right?

PHP namespaces allow us to circumvent this issue, in fact we can have as many User classes as we like. Not only that, but we can use namespaces to contain our similar code into neat little packages, or even to show ownership.

Using a class declared in a namespace

Classes in Global namespace can also be referred as :

$eddard = new \Eddard();

Namespaces can have as many levels of hierarchy as they need to.


What are php Lambdas and Closures?

What are PHP Lambdas and Closures?

What is a Lambda?
A Lambda is an anonymous function that is can be assigned to a variable or passed to another function as an argument. Because the function has no name, you can’t call it like a regular function. Instead you must either assign it to a variable or pass it to another function as an argument.

Lambdas are useful because they are throw away functions that you can use once. Often, you will need a function to do a job, but it doesn’t make sense to have it within the global scope or to even make it available as part of your code. Instead of having a function used once and then left lying around, you can use a Lambda instead.

What is a closure ?
A Closure is essentially the same as a Lambda apart from it can access variables outside the scope that it was created.
// Create a user
$user = "Philip";

// Create a Closure
$greeting = function() use ($user) {
echo "Hello $user";

// Greet the user
$greeting(); // Returns "Hello Philip"

As you can see above, the Closure is able to access the $user variable. because it was declared in the use clause of the Closure function definition.

If you were to alter the $user variable within the Closure, it would not effect the original variable. To update the original variable, we can append an ampersand.