PHP New Major Version

When you see a change in the major version (the number before the first point of the version id), expect a great leap. New features have been added to PHP in version 7, that make programming more convenient. I’m going to discuss some of them.

Null Coalescing

Suppose you’re trying to get a value from a request, and set it to zero if not sent. So instead of typing

$val = $_GET['foo'];
if ($val == null)
  $val=0;

Simply use ?? as follows:

$val = $_GET['foo'] ?? 0;

The Spaceship Comparison Operator

When making a decision based on comparisons between to values, would you like to use a switch command instead of if ... else? Use the operator ‘<=>’ to compare numbers or strings.
$a<=>$b will return one of the following values:
* -1 if $a is smaller than $b
* 0 if $a equals $b
* 1 if $a is greater than $b

Generator Functions

Generator functions have been introduced in PHP 5.5. They allow you to elegantly use generated values in a foreachloop without calling the function time and time again.
For example, the following code:

<?php
function factUpTo($n){
  $genValue=1;
  for ($i=1; $i<=$n;$i++){
    $genValue *= $i;
    yield $genValue;
  }
}

foreach (factUpTo(8) as $j){
  print $j . "\n";
}
?>

produces the following output:

1
2
6
24
120
720
5040
40320

Following are features introduced in PHP 7:

Returned Values

In addition to generating values, a generator can return a value using the return command. This value will be retrieved by the caller using the method getReturn().

For example, the code:


<?php

$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

foreach ($gen as $val) {
    echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

will produce the output:

1
2
3

Delegation

A generator function can generate values using another generator function. This can be done by adding the keyword from after the command yield.
For example, the following code:


<?php
function gen()
{
    yield 1;
    yield 2;
    yield 4;
    yield from gen2();
}

function gen2()
{
    yield 8;
    yield 16;
}

foreach (gen() as $val)
{
    echo $val, PHP_EOL;
}
?>

will produce the following output

1
2
4
8
16

Return Type Declaration

A return type can be declare by adding it at the end of the function declaration after colons.
For example:

function myFunc(): int
{
.
.
.
return $retValue;
}

returns an integer.

Why Write The Return Type At The End?

Two possible reasons to write the type at the end of the declaration and not at the beginning like in Java, C, and other c-like languages:
* In PHP, the function declaration begins with the keyword funcction. The return type is optional.
* This syntax already exists in AcrionScript.

Find more about PHP 7 in the chapter Migrating from PHP 5.6.x to PHP 7.0.x of the php.net site documentation.

Written with StackEdit.

Advertisement

Static Variables in JavaScript

How do you declare a static variable in a JavaScript function?
Not with the word “static“.
In JavaScript “function” is a variable type similar to “object“.
The difference is that the reference to a function inside itself is not this but arguments.callee.
An example of using arguments.callee is the following function that returns itself:

function func(){
    return arguments.callee;
}

Adding Static Variables

You can add arguments to arguments.callee. To initialize it the first time, check first if it is not defined. For example:

if (typeof(arguments.callee.myStaticVar)!="undefined")
    arguments.callee.myStaticVar=0;

Following is an example function in [rhino(http://rhino.org) JavaScript(run from the command line):

    function _example(){
        var thisFunction = arguments.callee;
        if (!thisFunction.static){
            thisFunction.static=0;
        }
        ++thisFunction.static;
        print("This function has been called: " + thisFunction.static + " times");
    };

In this example, you can change the static variable’s value without calling the function using _example.static = "some value";.

To prevent this, encapsulate your function using a function called once, for example:

(function(){
    function _example(){
        var thisFunction = arguments.callee;
        if (!thisFunction.static){
            thisFunction.static=0;
        }
        ++thisFunction.static;
        print("This function has been called: " + thisFunction.static + " times");
    };

    example=function(){
        _example();
    }
})();

Now, each time example() is called, it will increment the variablestatic, but the variable cannot be incremented without calling example because _example is private.

Written with StackEdit.

Asynchronous Operations In Node.js

Node.js is a JavaScript server-side framework. One of the things you can do easily with it is write a HTTP server.

a simple “Hello, world” server looks like:

http = require ('http');
http.createServer(function(request, response){
  response.write("Hello, world");
  response.end();
}).listen(8888);

Now, if you run the simple server and type ‘http://127.0.0.1:8888&#8217; in the URL bar of your browser you’ll see the text “Hello, world” in the browser’s window.

I’m sure you’re going to use Node.js for things more complicated than “Hello, world” programs. This server is one process that receive a request and sends a response. Other servers may perform operations that take longer, and we don’t want an operation to block the server from performing other tasks, such as handling other requests.
Node.js allows you to performs those operation in a non-blocking manner by providing the developer with function that accept a callback function as their last parameter. Those function are performed in another thread, and call the callback function upon completion.

The example I want to show you is a code fragment for disk I/O opeerations:

fs=require('fs');

fs.open('a.txt','w', function(err, fd){
  if (err)
    throw err;
  buffer=new Buffer("some long text");
  bufferLen=buffer.length;
  bytesWrittenSoFar = 0;
  pos=0;
  (function writeIt(){
    console.log('Buffer Len ' + bufferLen + ', Bytes Written ' + bytesWrittenSoFar);
    fs.write(fd,buffer,bytesWrittenSoFar, bufferLen - bytesWrittenSoFar, null, function(err,writtenBytes){
      if (err)
        throw err;
      if (bytesWrittenSoFar == bufferLen){
        console.log('Done!');
      } else {
        bytesWrittenSoFar += writtenBytes;
        writeIt();
      }
    });
  })();
});

How Does It Work?

In this example you can see two asynchronous function:

  • ‘fs.open’, that opens the file, and as the file is open calls the callback function, its 3rd argument.
  • fs.write – that attempts to write the output, and then calls the function ‘writeIt’.

This callback functions are called upon completion of opening a file, or writing it. The completion may be successful or unsuccessful. If unsuccessful, error handling should take place.

The Function WriteIt

The function ‘writeIt’ is a function which is defined and immediately performed. This function is called asynchronously, and until all the data is written, it keeps calling itself. We cannot perform this task using a loop, because a loop will create threads running in parallel. Therefore we use “asynchronous recursion”.

File System function with a simpler syntax have the suffix ‘Sync’ at the end of their names. Those functions you would usually want to avoid, so instead of having the default names, they have a name with a suffix.

Learn more about how to program in Node.js here, and maybe purchase a tutorial with exercises.

Find documentation about Node.js modules and functions here.