Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

PHP - Traits, Namespaces, Closures, Generators, Late Static Binding and More

Traits, Namespaces, Closures ( Anonymous functiontions ), Generators ( Yield keyword ), Late Static Binding and more.
by

Khwab Sheth

on 4 February 2014

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of PHP - Traits, Namespaces, Closures, Generators, Late Static Binding and More

Closures/
Anonymous functions (5.3)
Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.
Generators
( yield keyword )
Namespaces
In the broadest definition namespaces are a way
of encapsulating items.
Topics
Closures( Lambda/Anonymous functions) (5.3)
Traits ( 5.4)
Namespaces (5.3)
Generators ( yield keyword ) ( 5.5)
Finally with try and catch ( 5.5 )
Jump Labels (5.3)
Changes in empty function ( 5.5 )
Late static binding (5.3)
Traits
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.
PHP 5.3 and Above
Example

<?php
$greet = function($name) {
printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

Output:
Hello World
Hello PHP
Example
/*file1.php*/
namespace App\File1;
const MYCONST = 'File1.php';

/*file2.php*/
namespace App\File2;
const MYCONST = 'File2.php';

/*mainfile.php*/
require_once('file1.php');
require_once('file2.php');

echo App\File1\MYCONST;
echo App\File2\MYCONST;
Closures may also inherit
variables from the parent
scope using 'use' keyword.
public function getTotal($tax) {
$total = 2;
$callback = function ($quantity)
use ($tax, $total)
{
// $tax and $total can be accessed here.
};
array_walk($this->products, $callback);
}
Example
public function getTotal($tax) {
$total = 2;
$callback = function ($quantity){
echo $total;
echo $tax;
echo $quantity;
};
array_walk($this->products, $callback);
}
Output
Notice: Undefined variable: tax in C:\svn\...
Notice: Undefined variable: total in C:\svn\...
Example

class Base {
public function sayHello() {
echo 'Hello ';
}
}
trait SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}
class MyHelloWorld extends Base {
use SayWorld;
}
$o = new MyHelloWorld();
$o->sayHello();

Oputput: Hello World!
class BaseClass {
function SomeMethod() { /* Do stuff here */ }
}
interface IBase {
function SomeMethod();
}
trait myTrait {
function SomeMethod() { /* Do different stuff here */ }
}
class MyClass extends BaseClass implements IBase {
use myTrait;
function SomeMethod() { /* Do a third thing */ }
}

Precedence
Example

function generateSeries() {
for ($i = 1; $i <= 6; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}

$generator = generateSeries();
foreach ($generator as $value) {
echo "$value\n";
}
The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
Benefits
Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
Thank You
-Khwab Sheth
khwab@ymail.com
Finally keyword
with try and catch
try {
echo inverse( 0 );
} catch( Exception $e ) {
echo 'Exception: ', $e->getMessage();
}
finally
{
echo 'I am always called';
}
Jump Labels
The goto operator can be used to jump to another section in the program. The target point is specified by a label followed by a colon, and the instruction is given as goto followed by the desired target label.
Example
Example1:
goto a;
echo 'Foo1';
a: echo 'Bar1';

goto A;
echo 'Foo2';
A: echo 'Bar2';

Output
:
Bar1 Bar2
Example2:
for($j=50; $j>1; $j--) {
if($j==15) goto end;
echo "j = $j" . '<br>';
}
end: echo 'j hit 15';

Output:
j=50...j=16
j hit 15
'empty' function
Changes in
Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error.
In other words, the following will not work: empty(trim($name))
The Interface IBase requires a parameterless function called SomeMethod() to be provided.
The base class BaseClass provides an implementation of this method - satisfying the need.
The trait myTrait provides a parameterless function called SomeMethod() as well, which takes precedence over the BaseClass-version.
The class MyClass provides its own version of SomeMethod() - which takes precedence over the trait-version.
Few hand-picked features supported from 5.3 which could help you in your day to day programming.
Conflict Resolution and Aliasing
class Player {
use Game, Music {
Game::play as gamePlay;
Music::play insteadof Game;
}
}

$player = new Player();
$player->play();
//Playing music
$player->gamePlay();
//Playing a game
trait Game {
function play() {
echo 'Playing a game';
}
}

trait Music {
function play() {
echo 'Playing music';
}
}
References
http://php.net/
http://www.sitepoint.com/using-traits-in-php-5-4/
http://sandbox.onlinephpfunctions.com/
http://www.lornajane.net/posts/2009/php-5-3-feature-late-static-binding
Late static binding
"Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information.
Example
class Car {
protected static $strName = 'Car';
public static function getName() {
echo self::$strName; //Prints Car
echo
static
::$strName; //Prints Toyota
}
}

class Toyota extends Car {
protected static $strName = 'Toyota';
}

Toyota::getName();
Memory
consumption
$data = range(0, 1000000);
echo sprintf('%02.2f', (memory_get_usage() / 1048576))." MB of memory used\n";
//Output: 80.65 MB of memory used
function range_yield($intStart, $intEnd) {
for ($index = $intStart; $index <= $intEnd; $index++) {
yield $index => $index;
}
}

$data = range_yield(0, 1000000);
echo sprintf('%02.2f', (memory_get_usage() / 1048576))." MB of memory used\n";
//Output: 0.22 MB of memory used

It was also called a "static binding" as it can be used for static method calls.
Full transcript