Advanced Features of PHP

1) 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.

class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();

Instead of “self::who()” replace with “static::who()”. Then the output will be “B” instead of “A”.

2) Variable Length Argument Lists :

func_num_args() ==> returns number of arguments passed
func_get_arg(int) ==> returns the nth argument passed in
func_get_args() ==> returns an array of all arguments

New Features in PHP 7

https://blog.feryn.eu/php-7-is-now-available-new-features-improvements/

1) Speed

2) Type Declarations:
Since PHP 5, you can use type hinting to specify the expected data type of an argument in a function declaration, but only in the declaration.  Besides only being used in function declarations, we were also limited to basically 2 types. A class name or an array.  When you call the function, PHP will check whether or not the arguments are of the specified type. With PHP 7 we now have added Scalar types. Specifically: int, float, string, and bool.

function stringTest(string $string) {
    echo $string;
 }

Additionally, PHP 7 gives us the opportunity to enable strict mode on a file by file basis. We do this by declare(strict_types=1); at the top of any given file.

PHP 7 also supports Return Type Declarations which support all the same types as arguments. To specify the return type, we add a colon and then the type right before the opening curly bracket.

function getTotal(float $a, float $b) : float {

3) Error Handling :
In PHP 7, an exception will be thrown when a fatal and recoverable error occurs, rather than just stopping the script. Fatal errors still exist for certain conditions, such as running out of memory, and still behave as before by immediately stopping the script. An uncaught exception will also continue to be a fatal error in PHP 7. This means if an exception thrown from an error that was fatal in PHP 5 goes uncaught, it will still be a fatal error in PHP 7.

A big change in PHP 7 is the fact that errors are no longer raised the way they used to be raised. Errors now behave in a similar way as exceptions. This means that errors can now be caught in a try/catch block. You can catch both exceptions and errors as Throwables, but you can also catch errors as Error objects. We point out that other types of errors such as warnings and notices remain unchanged in PHP 7. Only fatal and recoverable errors throw exceptions.

interface Throwable
    |- Exception implements Throwable
        |- ...
    |- Error implements Throwable
        |- TypeError extends Error
        |- ParseError extends Error
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error

Throwable may be used in try/catch blocks to catch both Exception and Error objects (or any possible future exception types). Remember that it is better practice to catch more specific exception classes and handle each accordingly. However, some situations warrant catching any exception (such as for logging or framework error handling). In PHP 7, these catch-all blocks should catch Throwable instead of Exception.

4) New Operators (Spaceship Operator, Null Coalesce Operator) :

Spaceship Operator (useful in sort algorithms, etc)

$compare = 2 <=> 1
2 < 1? return -1 2 = 1? return 0 2 > 1? return 1

the Null Coalesce Operator, is effectively the fabled if-set-or.
If $firstName is empty then set it to Guest.

$name = $firstName ??  "Guest";

Can be chained.

$name = $firstName ?? $username ?? $placeholder ?? “Guest”; 


5) Anonymous Classes :

Anonymous classes are useful when simple, one-off objects need to be created.

$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

http://blog.teamtreehouse.com/5-new-features-php-7

6) Closure:Call() Method:

Closures are anonymous functions that are declared inline and assigned to a variable. It can be used as a callback for later execution. In PHP 5 it was already possible to bind an object to the scope of the closure as if it was a method.

The “call” method is one of the PHP 7 features that was introduced to simplify the process.

Given a sequence of words, print all anagrams together

$sortFunc = function($val) {
   $strArr = str_split($val);
   sort($strArr);
   return implode("", $strArr);
};

$arr = array("cat", "dog", "tac", "god", "act");

$words = array();
$index = array();

// form a new array with each string sorted within itself
$words = array_map($sortFunc, $arr);
// form a index array in order to remember original index
foreach ($words as $key => $val) {
    $index[$key] = $val;
}
asort($index);  // sort the values but maintain index association
foreach ($index as $key => $val) {
    // use index value in the original array to print
    echo $arr[$key] . "\n";
}

http://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/

Interesting Algorithm Interview Questions

1) Sorting a list of words such anagrams are grouped together. (Soundhound.com)
Input: [‘abc’,’test’,’vac’, ‘bac’, ‘london’, ‘cba’, ‘cav’, ‘lon’, ‘pst’]
Output: [‘abc’, ‘bac’, ‘cba’, ‘vac’, ‘cav’, ‘london’, ‘test’, ‘lon’, ‘pst’]

2. Design Twitter algorithm to retrieve top 10 new feeds (Soundhound.com)

Stored Procedure vs Function in MySQL

* Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes whenever it is called. But Function is compiled and executed every time when it is called.
Stored

* Procedures are used as scripts and functions are used as methods

* Functions have a scalar return value. Procedures do not have a return value.

* A stored procedure may have arguments that are IN, OUT, or INOUT. Functions may only have IN arguments.

* To invoke a stored procedure, use the CALL statement. To invoke a stored function, refer to it in an expression

Find a substring within a string and return the index where it was found


$bigString = "I am a really big realtor in the bay area";
$pattern = "realtor";

$i = 0;
$j = 0;
$bigStringLen = strlen($bigString);
$patternLen = strlen($pattern);
$found = false;
while ($i <= ($bigStringLen - $patternLen)) {
   if ($bigString[$i] == $pattern[$j]) {

   } else {
       $j=0;
   }
   $i++; $j++;
   if ($j >= $patternLen) {
       $found = true;
       break;
   }
}
if ($found) {
    print "found at " . ($i-$patternLen) . "\n";
} else {
    echo "\nnot found\n";
}

Ten-X Interview

1) Write a javascript function to print an array slowly (e.g each element in intervals of 500 ms). Example of array : 1,5,6,’cool’,8. Once done then print “all done”.

Method-1

var arr = [1,5,6,"cool",8];

function foo(i) {
   console.log("i:" + i + ":" + arr[i]);

}

function foo2() {
   console.log("all done");
}

for (i=1; i <=3 ; i++) {
    setTimeout(foo, i*500, i);
}

setTimeout(foo2, (i)*500);

Disadvantage in Method-1 is that so many setTimeout will be in memory. In Method-2 the number of setTimeout in memory will be less.

Method-2

var arr = [1,5,6,'cool', 8];

function foo(i) {
if (i < arr.length) {
console.log("i:" + i + ":" + arr[i]);
setTimeout(foo, 500, i+1);
} else {
console.log("all done");
}
}

setTimeout(foo, 500, 0);

Method-3

const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  // using the ES6 let syntax, it creates a new binding
  // every single time the function is called
  // read more here: http://exploringjs.com/es6/ch_variables.html#sec_let-const-loop-heads
  setTimeout(function() {
    console.log('The index of this number is: ' + i);
  }, 3000*i);

Method-4

for (i = 0, max = 9; i < max ; i ++) {
  setTimeout(printFunc(i), 500*i);
}

function printFunc(i) {
   return function() {
       console.log(i);
   }
}

Method-5. (Using IIFE – Immediately Invoked Function Expression)

var arr = [1,5,6,"cool",8];

for (i=0; i < arr.length ; i++) {
   (function(i) {
    setTimeout(foo, i*1500, i);
   }(i))
}
function foo(i) {
   console.log("i:" + i + ":" + arr[i]);

}

function foo2() {
   console.log("all done");
}


setTimeout(foo2, (i)*1500);

 

2) Given a string “San Francisco Hotel” and a array of strings (e.g. San Jose Culture of Art, Father Francisco and San Mateo”, “Yahoo”, “I love Hotel”) etc find out the best match. For example in above “Father Francisco and San Mateo is best match since it contains San and Francisco.

You can index all given individual strings. For example “San”, “Jose”, “Culture”, “Art”, etc  mapping name to index of string where it appears.

San ==> array(0,1)

Jose ==> array (0)

Culture ==> array(0)

Art ==> array(0)

Father ==> array(1)

Francisco ==> array(1)

Mateo ==> array(1)

Hotel ==> array(3)

Then to search for an input string, You can get all the results for each word in the input string and combine the resultant set in a hash which contains which word occurs how many times.

For San Francisco Hotel you will need to show strings : 0,1,3 for sure. However to rank these strings you can use a hash which will show you which word appears more times.

result[1] ==> 2  (string at index 1 contains 2 matching words)

result[0] ==> 1 (string at index 0 contains 1 matching word)

result[3] ==> 1  (string at index 3 contains 1 matching word)

 

3) Given a sorted array return a random array.

4) Given an array of N numbers return the max product of 3 numbers. Example if the array contains [4,2,7,5,3] then the max product possible is 4 * 7 * 5 = 140.

5) In Javascript Using functional programming , given an array of numbers, return the sum of their squares.

var arr = [2,4,6,8];

var sum = arr.map(function(s) { return s*s;}).reduce(function(acc, val) {return acc + val;});