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.

Javascript Prototype Pattern

1. First, there is a prototype property that every JavaScript function has (it is empty by default), and you attach properties and methods on this prototype property when you want to implement inheritance.Note that this prototype property is not enumerable: it is not accessible in a for/in loop. The prototype property is used primarily for inheritance: you add methods and properties on a function’s prototype property to make those methods and properties available to instances of that function.

2. The second concept with prototype in JavaScript is the prototype attribute. Think of the prototype attribute as a characteristic of the object; this characteristic tells us the object’s “parent”. In simple terms: An object’s prototype attribute points to the object’s “parent”—the object it inherited its properties from. The prototype attribute is normally referred to as the prototype object

Prototype is important in JavaScript because JavaScript does not have classical inheritance based on Classes (as most object oriented languages do), and therefore all inheritance in JavaScript is made possible through the prototype property. JavaScript has a prototype-based inheritance mechanism.

function Plant () { = "Mexico";
this.isOrganic = true;

// Add the showNameAndColor method to the Plant prototype property
Plant.prototype.showNameAndColor =  function () {
console.log("I am a " + + " and my color is " + this.color);

// Add the amIOrganic method to the Plant prototype property
Plant.prototype.amIOrganic = function () {
if (this.isOrganic)
console.log("I am organic, Baby!");

function Fruit (fruitName, fruitColor) { = fruitName;
this.color = fruitColor;

// Set the Fruit's prototype to Plant's constructor, thus inheriting all of Plant.prototype methods and properties.
Fruit.prototype = new Plant ();

// Creates a new object, aBanana, with the Fruit constructor
var aBanana = new Fruit ("Banana", "Yellow");

// Here, aBanana uses the name property from the aBanana object prototype, which is Fruit.prototype:
console.log(; // Banana

// Uses the showNameAndColor method from the Fruit object prototype, which is Plant.prototype. The aBanana object inherits all the properties and methods from both the Plant and Fruit functions.
console.log(aBanana.showNameAndColor()); // I am a Banana and my color is yellow.

Prototype is also important for accessing properties and methods of objects. The prototype attribute (or prototype object) of any object is the “parent” object where the inherited properties were originally defined. if you want to access a property of an object, the search for the property begins directly on the object. If the JS runtime can’t find the property there, it then looks for the property on the object’s prototype—the object it inherited its properties from.This in essence is the prototype chain

var myFriends = {name: "Pete"};

// To find the name property below, the search will begin directly on the myFriends object and will immediately find the name property because we defined the property name on the myFriend object. This could be thought of as a prototype chain with one link.

// In this example, the search for the toString () method will also begin on the myFriends’ object, but because we never created a toString method on the myFriends object, the compiler will then search for it on the myFriends prototype (the object which it inherited its properties from).

// And since all objects created with the object literal inherits from Object.prototype, the toString method will be found on Object.prototype—see important note below for all properties inherited from Object.prototype. 

myFriends.toString ();

When it comes to inheritance, JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

var o = {a: 1};

// The newly created object o has Object.prototype as its [[Prototype]]
// o has no own property named 'hasOwnProperty'
// hasOwnProperty is an own property of Object.prototype. 
// So o inherits hasOwnProperty from Object.prototype
// Object.prototype has null as its prototype.
// o ---> Object.prototype ---> null

var a = ["yo", "whadup", "?"];

// Arrays inherit from Array.prototype 
// (which has methods like indexOf, forEach, etc.)
// The prototype chain looks like:
// a ---> Array.prototype ---> Object.prototype ---> null

function f() {
  return 2;

// Functions inherit from Function.prototype 
// (which has methods like call, bind, etc.)
// f ---> Function.prototype ---> Object.prototype ---> null

Javascript Set2 of Interview questions

1) Does Javascript support read only attributes of Object?

With any javascript interpreter that implements ECMAScript 5 you can use Object.defineProperty to define readonly properties. In loose mode the interpreter will ignore a write on the property, in strict mode it will throw an exception.

var obj = {};
Object.defineProperty( obj, "", {
  value: "",
  writable: false,
  enumerable: true,
  configurable: true

Also you can try to attempt this via private attributes simulation.

2) What does the delete operator do ?
delete is used to delete object properties. It will not delete ordinary variables defined with var. it will delete global variables though since they are actually properties of the global object.

3) What are all the types of Pop up boxes available in JavaScript?

Confirm and

4) What does the void operator do
The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value). undefined isn’t a JavaScript keyword, but a property of the global object. So it can be shawdowed sometimes.

5) What does use strict in javascript do ? What kind of errors does it catch ?
If you use “use strict” javascript will flag error for certain cases.

x = 3.14; // will cause error since x is not declared
x = {p1:10, p2:20}; // using object without declaring it
var x = 3.14; delete x; // deleting a variable will cause an error
function x(p1, p2) {}; delete x; // deleting a function will cause an error
function x(p1, p1) {}; // Duplicating parameter names will cause an error

6) What is event bubbling and event capturing ?
Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.

With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

With capturing, the event is first captured by the outermost element and propagated to the inner elements.

We can use the addEventListener(type, listener, useCapture) to register event handlers for in either bubbling (default) or capturing mode. To use the capturing model pass the third argument as true

7) What is hoisting in javascript ?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Inevitably, this means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.

Of note however, is the fact that the hoisting mechanism only moves the declaration. The assignments are left in place.

8) Make this work
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

var newarr = duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

function duplicate(arr) {
   return arr.concat(arr);

9) What’s the difference between feature detection, feature inference, and using the UA string?
When you check if a certain feature exists, that’s feature detection.
if(typeof(Text) === “function”){

When you make an assumption that because one feature is present (or not) another one will also be present (or not)
if(typeof applyElement != ‘undefined’) {
// now I know I’m not in IE, I’ll just assume Text is available
text = new Text(‘Oh, how quick that fox was!’);

“UA” stands for user agent, which means the browser (and a whole lot of other stuff). Just like with feature inference, if you use the UA string you’re making an assumption about how the string will be written, what changes are likely to happen in this particular version. Using UA string to infer things is also bad.

10) What does the javascript comma operator do ?
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand. (MDC)

var a = (7, 5);
a; //5
var x, y, z
x = (y=1, z=4);
x; //4
y; //1
z; //4

Scope of variables in Javascript

Javascript has two types of scopes global and local(function) level scope. Variables declared globally that are visible throughout the javascript program come under global scope. Variables declared inside functions, may have same name as global varibles, are accessible only within that function are local variables.

1) No block level scope(except a special case – Block-scoped variables)
2) Variables are hoisted (variables declaration are moved to top and then run)
3) Chaining of scopes. Any function defined within another function has a local scope which is linked to the outer function.

Also any property assigned to window object is also treated as global variable.

If variables are defined without var(no var) outside functions, they are treated as global variable. “no var” variable definition inside function will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).


JSON : Javascript Object Notation

JSON syntax is a subset of the JavaScript object notation syntax:

– Data is in name/value pairs
– Data is separated by commas
– Curly braces hold objects
– Square brackets hold arrays

JSON values can be:

A number (integer or floating point)
A string (in double quotes)
A Boolean (true or false)
An array (in square brackets)
An object (in curly braces)

  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "height_cm": 167.6,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  "phoneNumbers": [
      "type": "home",
      "number": "212 555-1234"
      "type": "office",
      "number": "646 555-4567"
  "children": [],
  "spouse": null

Advantages of JSON:
– JSON is more compact
– can be easily loaded in JavaScript. (but using eval() in JS is security risk. So use a language json parser like JSON.parse).
– JSON parsing is generally faster than XML parsing
– Formatted JSON is generally easier to read than formatted XML.
– JSON specifies how to represent complex datatypes, there is no single best way to represent a data structure in XML.
– More structural information in the document
— Can easily distinguish between the number 1 and the string “1” as numbers, strings (and Booleans) are represented differently in JSON.
— Can easily distinguish between single items and collections of size one (using JSON arrays).
Easier to represent a null value

Advantages of XML:
– XML tends to have broader tool support and is more easily queryable (for example, using XPath)
– XML is stricter
– has support for schemas – I.e. the ability for party A to specify the format of a document, and the ability for party B to check that they are supplying something that matches this format.
– has support for namespaces – I.e. the ability to mix data intended to be read by multiple sources (or written by multiple sources) in the same document.
– XML is best used when transporting something like a patient chart or text document with markup included
– XML has XSLT and XPath. So you have your data in one format but you want it in another. If the data is in XML, you can write an XSLT template and run it over the XML to output the data into another format. Using XPath, it’s possible to get direct access to a part of multiple parts of an XML data structure
– JSON is not expressive enough to separate attributes from values. XML can do that.

Algorithms on Graphs

1) DFS
Remember its recursive

2) BFS
Queue based

3) Shortest Path in unweighted graph.

4) Shortest Path in weighted graph.

5) Determine if directed graph has a cycle
Karumanchi , pg 236

If a node is seen a second time before all of its descendants are visited then there is a cycle.

Detect Cycle(G) {
  Initialize Visited array and Predecessor array; 
  call HasCycle

HasCycle(G, u) {
 Visited[u] = true; 
 Loop i over all vertices v
   Check if edge present in Adjacency Matrix 
      If Predecessor P[i] != u and Visited[u] then 
          Cycle exists; 

Depth First Search vs Breadth First Search

Karumanchi (pg 216)

1) Visit a node, then one of its child, then one of its child, till you reach the leaf. Then backtrack and visit other childs.
2) lower memory requirements since its not required to store all child pointers at each level.
3) If data being looked for has more probability of being at the bottom of the tree, then DFS is a good fit.
4) DFS works off a stack
5) Example: Good for solving puzzles such as mazes, finding strongly connected components (Finding Strongly Connected Components of a graph A directed graph is called strongly connected if there is a path from each vertex in the graph to every other vertex).
6) Simple algo is recursive

1) more memory than DFS
2) If data being looked for has more probability of being at top of the tree then BFS is a good fit.
3) It visits all vertices at level 1 before proceeding ahead. Then it visits all vertices at level 2. Is similar to level order traversal of trees.
4) BFS works off a queue
5) Example: shortest path,
6) simple algo is non recursive (with a while loop)

Questions on Testing

1) Difference between functional testing and unit testing
Unit Tests are written from a programmers perspective. They are made to ensure that a particular method (or a unit) of a class performs a set of specific tasks.

Functional Tests are written from the user’s perspective. They ensure that the system is functioning as users are expecting it to.

2) What is TDD (Test Driven Development)

3) What is a “mock” and “stub”?
They are both fake objects.

– Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it ‘sent’, or maybe only how many messages it ‘sent’.
– State Testing

Setup – Prepare object that is being tested and its stubs collaborators.
Exercise – Test the functionality.
Verify state – Use asserts to check object’s state.
Teardown – Clean up resources.

– objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
– Behavioral Testing
– Test lifecycle with mocks:

Setup data – Prepare object that is being tested.
Setup expectations – Prepare expectations in mock that is being used by primary object.
Exercise – Test the functionality.
Verify expectations – Verify that correct methods has been invoked in mock.
Verify state – Use asserts to check object’s state.
Teardown – Clean up resources.

Both mocks and stubs testing give an answer for the question: What is the result?

Testing with mocks are also interested in: How the result has been achieved?

Mocks vs Stubs = Behavioral testing vs State testing


I believe the biggest distinction is that a stub you have already written with predetermined behavior. So you would have a class that implements the dependency (abstract class or interface most likely) you are faking for testing purposes and the methods would just be stubbed out with set responses. They would not do anything fancy and you would have already written the stubbed code for it outside of your test.


A mock is something that as part of your test you have to setup with your expectations. A mock is not setup in a predetermined way so you have code that does it in your test. Mocks in a way are determined at runtime since the code that sets the expectations has to run before they do anything.


Tests written with mocks usually follow an initialize -> set expectations -> exercise -> verify pattern to testing. While the pre-written stub would follow an initialize -> exercise -> verify.


The purpose of both is to eliminate testing all the dependencies of a class or function so your tests are more focused and simpler in what they are trying to prove.

Stub – override methods to return hard-coded values, also referred to as state-based.
Example: Your test class depends on a method Calculate() taking 5 minutes to complete. Rather than wait for 5 minutes you can replace its real implementation with stub that returns hard-coded values; taking only a small fraction of the time.

Mock – very similar to Stub but interaction-based rather than state-based. This means you don’t expect from Mock to return some value, but to assume that specific order of method calls are made.
Example: You’re testing a user registration class. After calling Save, it should call SendConfirmationEmail.