Tuesday, November 19, 2019

Object Oriented Programming (OOP) in Layman's Terms

Object Oriented Programming System (OOPs) is a programming model based on the concept of "objects" that contain data and methods.
The primary purpose of object-oriented programming is to increase the flexibility and maintainability of programs.
Object Oriented Programming brings together data and its behavior (methods) in a single location (object) makes it easier to understand how a program works.

Class & Object

First of all, let's see the formal definition of class and object:

A class is a blueprint, or prototype, that defines the variables and the methods common to all objects of a certain kind.
An object is a software bundle of variables and related methods. 

Everything around us is an OBJECT like a car, a pencil, a table, a dog, you and me. Each object belongs to a particular CLASS.



For example, if I ask you to tell me the similarity between dog, cat, lion, zebra then you will say that all of these are animals which means all of them to belong to a class Animal.


Similarly, if I say table, chair, shelf then we can say that these all are furniture. That means all these objects belong to a class Furniture.

We can also say that objects are proper nouns and classes are common nouns.

These classes can be further subdivided into more classes to give more details about the group of objects they contain. For example, the class Animal given above can be further subdivided into two classes as Wild Animals and Domestic Animals and the class Furniture can be subdivided into two classes as Wooden Furniture and Steel Furniture. This is the concept behind inheritance.

Every object has states and behavior. Let’s take an example of a class Animal and its object dog. Now as we all know that a dog has states - name, color, breed etc. and behavior - barking, running, fetching, wagging tail, etc.

These states are called Variables and behavior are called methods or functions. Now we can define these variables and methods in class Animal and can call these methods anytime after creation of its object a dog.

Think of everything as an object and assign classes to them.

Abstraction

You have a bike. In the bike there is a clutch on left hand, front brake on right hand, gears on left leg and rear brake or right leg. Using these four you control your bike while driving. You don’t know how engine internally works when these are applied. You only need to know how to apply these. This is abstraction. And brake, gears , clutch are interfaces.

Internally drum brake will be replaced via disc brake, 100 cc engine will be replaced via 200 cc engine but the interface will remain unchanged. Also, even you switch the bike you will get the same interface (almost).

Encapsulation

Encapsulation can be referred as information hiding. How bike engine is internally implemented, how it interacts with the several parts of the bike like wheel, fuel tank etc. is completely hidden. You can access functionality of the bike only with the interfaces exposed. You can start a bike with the key only. If bike has some flaw that you can even start it without key that we can say that bike is not encapsulated.

Inheritance

There are some properties of bike like gears, clutch, brake. Every bike contains these properties. Hero bike also contains these properties. Bajaj bike also contains these properties. So we can say that Hero is also bike and Bajaj is also a bike. Also Hero is not Bajaj, as it differs than Hero in some mean. This is inheritance. Inheritance is an IS-A property.

Polymorphism

Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.



Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person present in different-different behaviors.



Friday, September 13, 2019

Swapping Two Numbers Without Using Third Variable in PHP

Given two variables a and b, swap two variables without using a third variable.



Method (Using Arithmetic Operators)
The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.



<?php
// PHP Program to swap two numbers without third variable
$a = 25;
$b = 19;

echo "a before swapping : ", $a;
echo "b before swapping : ", $b;

// code to swap numbers

$a = $a + $b; // a becomes 44 now
$b = $a - $b; // b becomes 25 now
$a = $a - $b; // a becomes 19 now

echo "a after swapping : ", $a;
echo "b after swapping : ", $b;
?>

OUTPUT:
a before swapping : 25
b before swapping : 19

a after swapping 19
b after swapping 25

Wednesday, June 26, 2019

echo vs print Statement in PHP

There are two basic ways to get output in PHP:
  • echo
  • print

PHP echo statement

In PHP echo statement is a language construct and not a function, so it can be used without parentheses. But we are allowed to use parentheses with echo statement when we are using more than one arguments with it. The end of the echo statement is identified by the semi-colon (';').
We can use echo to output strings or variables. Below are some of the usage of echo statement in PHP:

Displaying Strings: We can simply use the keyword echo followed by the string to be displayed within quotes. Below example shows how to display strings with PHP:

<?php
echo "Hello, This is echo vs print statement!";
?>

Output: Hello, This is echo vs print statement!

Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement instead of a single string argument, separating them by comma (,) operator.

<?php
echo "Hello!", "PHP", "World";
?>

Output: Hello! PHP World

PHP print statement

The PHP print statement is similar to the echo statement and can be used alternative to echo at many times. It is also language construct and so we may not use parentheses: print or print().
Like echo, print statement can also be used to print strings and variables. Below are some examples of using print statement in PHP:

Displaying String of Text: We can display strings with print statement in the same way  as we did with echo statements. The only difference is, we cannot display multiple strings separated by comma(,) with a single print statement.

<?php
print "Hello World!";
?>
Output: Hello World!


Difference Between echo and print Statement

  • echo can accept multiple arguments while print only accepts a single argument
  • echo doesn't have a return value while print always returns 1
  • echo is marginally faster than print


Sunday, October 21, 2018

Advance Node.JS Interview Questions And Answers

Now a days NodeJs is very popular in the industry. If you're looking for Node.JS Interview Questions for Experienced or Beginners, you are at right place. There are lot of opportunities from many reputed companies in the world. According to research Node.JS has a market share of about 2.6%. So, You still have opportunity to move ahead in your career in Node.JS Development. Techbowl arranged Advanced Node JS Interview Questions 2018 or node js programming interview questions that helps you in cracking your interview & acquire dream career as Node.JS Developer.

Advance Node.JS Interview Questions And Answers


Advance Node.JS Interview Questions And Answers



Q1: What is Node.js?

Node.js is a web application framework built on Google Chrome's JavaScript Engine (V8 Engine).

Node.js comes with runtime environment on which a Javascript based script can be interpreted and executed (It is analogus to JVM to JAVA byte code). This runtime allows to execute a JavaScript code on any machine outside a browser. Because of this runtime of Node.js, JavaScript is now can be executed on server as well.


Node.js = Runtime Environment + JavaScript Library

Q2: What is an error-first callback?

Error-first callbacks are used to pass errors and data. The first argument is always an error object that the programmer has to check if something went wrong. Additional arguments are used to pass data.

fs.readFile(filePath, function(err, data) {
  if (err) {
    //handle the error
  }
  // use the data object
});


Q3: What are the benefits of using Node.js?

Following are main benefits of using Node.js

  • Aynchronous and Event Driven- All APIs of Node.js library are aynchronous that is non-blocking. It essentially means a Node.js based server never waits for a API to return data. Server moves to next API after calling it and a notification mechanism of Events of Node.js helps server to get response from the previous API call.
  • Very Fast- Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution.
  • Single Threaded but highly Scalable - Node.js uses a single threaded model with event looping. Event mechanism helps server to respond in a non-bloking ways and makes server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and same program can services much larger number of requests than traditional server like Apache HTTP Server.
  • No Buffering - Node.js applications never buffer any data. These applications simply output the data in chunks.

Q4: If Node.js is single threaded then how it handles concurrency?

Node provides a single thread to programmers so that code can be written easily and without bottleneck. Node internally uses multiple POSIX threads for various I/O operations such as File, DNS, Network calls etc.

When Node gets I/O request it creates or uses a thread to perform that I/O operation and once the operation is done, it pushes the result to the event queue. On each such event, event loop runs and checks the queue and if the execution stack of Node is empty then it adds the queue result to execution stack.

This is how Node manages concurrency.

Q5: What is global installation of dependencies?

Globally installed packages/dependencies are stored in /npm directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but can not be imported using require() in Node application directly. To install a Node project globally use -g flag.

Q6: How can you avoid callback hells?

To do so you have more options:

  • modularization: break callbacks into independent functions
  • use Promises
  • use yield with Generators and/or Promises
Q7: What's the event loop?

The event loop is what allows Node.js to perform non-blocking I/O operations — despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.



Every I/O requires a callback - once they are done they are pushed onto the event loop for execution. Since most modern kernels are multi-threaded, they can handle multiple operations executing in the background. When one of these operations completes, the kernel tells Node.js so that the appropriate callback may be added to the poll queue to eventually be executed.

Q8: How Node prevents blocking code?

By providing callback function. Callback function gets called whenever corresponding event triggered.

Q9: What is Event Emmitter?

All objects that emit events are members of EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object.

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously.

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
  console.log('an event occurred!');
});
myEmitter.emit('event');

Q10: What tools can be used to assure consistent code style?

You have plenty of options to do so:



These tools are really helpful when developing code in teams, to enforce a given style guide and to catch common errors using static analysis.

Q11: Provide some example of config file separation for dev and prod environments

A perfect and flawless configuration setup should ensure:
  • keys can be read from file AND from environment variable
  • secrets are kept outside committed code
  • config is hierarchical for easier findability
Consider the following config file:


 var config = {
 production: {
 mongo : { billing: '****' }
 },
 default: {
     mongo : { billing: '****' }
 }
 }
 exports.get = function get(env) { return config[env] || config.default; }
 

And it's usage:

const config = require('./config/config.js').get(process.env.NODE_ENV);
const dbconn = mongoose.createConnection(config.mongo.billing);



Saturday, October 20, 2018

Node.JS Interview Questions And Answers



Node.JS Interview Questions And Answers


Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser. Now a days NodeJs is very popular in the industry so, if you want to get hired in NodeJS interview, at least you should have good knowledge of Nodejs. Here we have collected some frequently asked questions of Nodejs. I hope you will get some help from these questions with answers.

Node.JS Interview Questions And Answers


 Q1) What is NodeJS?

NodeJS is javascript runtime environment that is built on chrome to enable lightweight and effective performance of server-side and networking applications in javascript. Node.js is a web application framework built on Google Chrome's JavaScript Engine (V8 Engine).

Node.js = Runtime Environment + JavaScript Library

Q2) What is NPM?

Node Package Manager(NPM). It is used to provide command line environment to install and manage NodeJS Packages, and NodeJS repositories that can be accessed at search.nodejs.org

Q3) Syntax to install modules using NPM. 

Syntax : $ npm install

Example: $ npm install express

var express = ('express'); 

Where express is Name of the module, 

express is JS file, that can be used in your module.

Q4) Mention types of npm modules available that are used very often.

Express, connect, socket.io and socketjs, pug, mongodb and mongojs, redis, lodash, forever, bluebird, moment are some of npm modules. 

Q5) Command to list modules installed in current npm. 

$ npm ls

Note: Remember not to mention npm in UPPERCASE - (Recommended) 

Q6) What are the attributes of package.json 

Name, version, description, homepage, author, contributors, dependencies − list of dependencies, repository − repository type and URL of the package, main − entry point of the package, keywords. 

Q7) What is REPL?

 REPL - Read, Eval, Print, Loop. 

It is an environment to input commands to perform REPL tasks. Each of the task is associated with its respective operations. 

Q8) What kind of applications can be built by Node.JS.

 DIRT, JSON, I/O Bound, Single Page applications are preferable to use Node.JS. 

Q9) What is the latest version of Node JS.

 Node v8.0.0 is the current version.

Q10) NodeJS is a framework. True or False. 

False. It is runtime or environment, but not a framework 

Q11) Commands to work with the file from the local database. 

 Var fs = require(‘fs’);
  • Read: fs.readFile(); 
  • Create: fs.appendFile(); fs.open(); fs.writeFile(); 
  • Write: fs. writeFile(); 
  • Delete: fs.unlink(); 
  • Rename: fs.rename(); 
  • Update: fs.appendFile() fs.writeFile()
Q12) What is error-first callback in Node JS? 

In order to check for proper working of the code, we need to verify error free execution. In this regard, error-first callbacks are used, that will send error first, followed by related data to the error. 

Q13) What is cluster? 

Cluster is a process to handle thread execution load while working with multi-core systems.

Q14) Why node is single threaded? 

In order to upgrade the performance well, single thread operations work better than multi-threaded operations. 

Q15) How does URL module works. 

This module helps URL to parse it into host, pathname, search, query, etc. 

Example: 
var url = require('url');
var adr = 'https://mindmajix.com/?s=node+js+training'; 
var q = url.parse(adr, true); 
console.log(q.host); //returns 'mindmajix.com' 
console.log(q.search); //returns '?s=node+js+training' 

Q16) Explain use of nodemailer module. 

It is not included in default modules list, it has to be installed using npm. 

Var nodemailer = require('nodemailer'); 

Q17) What are the types of versions available? 

Patch_Version, Minor_Version, Major_Version. 

Q18) What are event emitters in NodeJS? 

Objects in NodeJS will have to trigger events in order to maintain asynchronous execution of core API used. These objects that emit events are known as Event Emitters. 

Q19) What are event listeners? 

Events that are emitted by event emitters have to be listened in order to continue the asynchronous execution of the threads. These objects that listens the emitted events are known as listeners.

Thursday, July 20, 2017

New Features In PHP 7 That You Should Have A Look At

Now a days PHP is the most preferred programming language. But is PHP 7 the most exciting releases of them all? Yes. The whole PHP community and the people linked to PHP, are all excited to welcome the biggest release for PHP in decades. It surely adds more versatility to the already versatile language.

New Features In PHP 7

But you must be wondering why PHP named its latest release PHP 7 and not PHP 6. Reason behind it is that, many of the PHP 6 releases were already implemented in PHP 5.3 and later, there was not really a proper reason just to change the name. What I am trying to say here is that we haven't missed anything. Just to avoid the confusion with a dead project, PHP's latest release was named to PHP 7.

Let's take a deeper dive. Let's check out what new features PHP 7 has to offer. And what improvements those features will bring forth.

  • Performance (Speed Improvement)
  • Scalar Type Declarations
  • Return Type Declarations
  • Combined Comparison Operator
  • Null Coalesce Operator
  • Anonymous Classes
  • Unicode Codepoint Escape Syntax
  • Closure call() Method
  • Filtered unserialize()
  • IntlChar Class
  • Expectations
  • Group use Declarations
  • Generator Return Expressions
  • Generator Delegation
  • Integer Division with intdiv()
  • session_start() Options
  • preg_replace_callback_array() Function
  • CSPRNG Functions
  • Support for Array Constants in define()
  • Reflection Additions

Let's take a look on every feature in details:

Performance (Speed Improvement)


The developers for the PHP 7 has done a pretty commendable job here. Now your PHP codebase uses less memory and gives you even more performance than before. This is a result of refactoring the Zend Engine to use more compact data structures and less heap allocations/deallocations. The performance gains on real world applications will vary, though many applications seem to receive a ~100% performance boost - with lower memory consumption too! After it's release, internet was overloaded with benchmarks which were really promising. It is almost a 2x increase in server response times with PHP 7. For further details on benchmarks 


Scalar Type Declarations


PHP 7 has now added Scalar type declaration for int, float, string, and boolean. Adding scalar type declaration and enabling strict requirements ensures that more correct and well-documented PHP programs can be written. It also helps you in gaining more control over your code and make the code easier to read.
By default, on PHP 7, these declarations are non-strict. Which means that the type forging is possible. As if you pass a string starting with a number into a float type function, it grabs the number from in the start and skips everything else. Passing a float into a function that requires an int, that float will become int.

Non-Strict Example

[code]
function getSum(float $a, float $b) {
   return $a + $b;
}
getSum(6, "7 week");
//Here int(6) changed to float(6.0) and string "7 week" changed to float(7.0)
//with a "Notice: A non well formed numeric value encountered"
//returns float(13)
getSum(1.1, "2.2");
//Here string "2.2" is changed to float(2.2) without any notice
//returns float(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)
[/code]

Here the getSum function receives 2 floats and adds them together returning the sum. When you use a non-strict type declaration in PHP 7. It will reforge these arguments to match the type specified in the function. Which means whatever the argument we pass, PHP will convert it to float.

Strict Example

PHP 7 additionally gives us the opportunity to strict the declaration type. It is achieved by adding "strict_types=1" on the very first line of the file. This ensures that any calls made to the functions specified must strictly adhere to the specified types. Strict is determined in the file in which the call to a function is made and not the file in which the function is defined.
While using a strict type-declaration, if a mismatch occurs, a "Fatal Error" occurs and we know that something is not functioning as desired. This helps in not causing random and confusing diagnose issues. Let's just cut the talk and take a look at an example with strict types turned on.

declare(strict_types=1);
function getSum(float $a, float $b) {
    return $a + $b;
}

getSum(3, "2 week");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given

getSum(1.8,  "4.5");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given

getSum(3.1, 2);
// int(2) change to float(2.0)
//returns float(5.1)

Setting "declare strict_type" to "1", the first two calls that pass a string produces a Fatal error: "Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given". With only the exception in the third call, in which if you pass an integer for an argument instead of a float value, PHP will perform “widening”, which includes adding .0 at the end of the integer value. This returns (5.1).

Return Type Declaration


The third type of declaration that PHP 7 supports are a Return Type Declaration. It supports all similar type arguments as a return. Take look at the example of how to specify a return type declaration.

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

}

Adding a return type ensures that only an expected value type returns. For the previous two examples if we set the return type float it will work the same. As the values being returned are already float. So we will be doing an example for int. return types.

Non-Strict Integer Example

Without the strict type declaration on, if we specify the return type as int for the previous examples, it will work the same. With just the difference being, that return will be forged to an integer. Which means it will truncate the float value and only returns the integer.

function getSum(float $a, float $b) : int {
    return $a + $b;
}

getSum(6, "7 week");
// changes int(6) to float(6.0) & string("7 week") to float(7.0)
// returns int(13);

getSum(1.1, "2.2");
// changes string "2.2" to float(2.2)
// returns int(3.3)

getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)


Strict Integer Example

If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned. For this case we’ll be casting our return value as an int. which then returns the truncated value.

declare(strict_types=1);
function getSum(float $a, float $b) : int {
    // return $a + $b;
    // The above statement shows Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned
    return (int)($a + $b); // truncate float like non-strict
}
getSum(3.1, 2); // changes int(2) to float(2.0) and returns int(5.1)

Benefits
These new implementations of Type Declaration certainly help in making the code easier to read. With PHP 7 you get a versatile type declaration methods which makes your life easier. You can even see at the start of the function, what is required and what will be returned.

Combined Comparison Operator


The combined comparison operator (or spaceship operator) is a shorthand notation for performing three-way comparisons from two operands. It has an integer return value that can be either:


  • a positive integer (if the left-hand operand is greater than the right-hand operand)
  • 0 (if both operands are equal)
  • a negative integer (if the right-hand operand is greater than the left-hand operand)


The operator has the same precedence as the equality operators (==, !=, ===, !==) and has the exact same behaviour as the other loose comparison operators (<, >=, etc). It is also non-associative like them too, so chaining of the operands (like 1 <=> 2 <=> 3) is not allowed.

// compares strings lexically
var_dump('PHP' <=> 'Node'); // int(1)

// compares numbers by size
var_dump(123 <=> 456); // int(-1)

// compares corresponding array elements with one-another
var_dump(['a', 'b'] <=> ['a', 'b']); // int(0)
Objects are not comparable, and so using them as operands with this operator will result in undefined behaviour.

Null Coalesce Operator


The null coalesce operator (or isset ternary operator) is a shorthand notation for performing isset() checks in the ternary operator. This is a common thing to do in applications, and so a new syntax has been introduced for this exact purpose.

// Pre PHP 7 code
$route = isset($_GET['route']) ? $_GET['route'] : 'index';

// PHP 7+ code
$route = $_GET['route'] ?? 'index';


// compares corresponding array elements with one-another
var_dump(['a', 'b'] <=> ['a', 'b']); // int(0)
Objects are not comparable, and so using them as operands with this operator will result in undefined behaviour.

Null Coalesce Operator

The null coalesce operator (or isset ternary operator) is a shorthand notation for performing isset() checks in the ternary operator. This is a common thing to do in applications, and so a new syntax has been introduced for this exact purpose.

// Pre PHP 7 code
$route = isset($_GET['route']) ? $_GET['route'] : 'index';

// PHP 7+ code
$route = $_GET['route'] ?? 'index';

Anonymous Classes


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

// Pre PHP 7 code
class Logger
{
    public function log($msg)
    {
        echo $msg;
    }
}

$util->setLogger(new Logger());

// PHP 7+ code
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}

var_dump(new class(10) extends SomeClass implements SomeInterface {
    private $num;

    public function __construct($num)
    {
        $this->num = $num;
    }

    use SomeTrait;
});

/** Output:
object(class@anonymous)#1 (1) {
  ["Command line code0x104c5b612":"class@anonymous":private]=>
  int(10)
}
*/
Nesting an anonymous class within another class does not give it access to any private or protected methods or properties of that outer class. In order to use the outer class' protected properties or methods, the anonymous class can extend the outer class. To use the private or protected properties of the outer class in the anonymous class, they must be passed through its constructor:

<?php

class Outer
{
    private $prop = 1;
    protected $prop2 = 2;

    protected function func1()
    {
        return 3;
    }

    public function func2()
    {
        return new class($this->prop) extends Outer {
            private $prop3;

            public function __construct($prop)
            {
                $this->prop3 = $prop;
            }

            public function func3()
            {
                return $this->prop2 + $this->prop3 + $this->func1();
            }
        };
    }
}

echo (new Outer)->func2()->func3(); // 6

Unicode Codepoint Escape Syntax


This enables a UTF-8 encoded unicode codepoint to be output in either a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.

echo "\u{aa}"; // ª
echo "\u{0000aa}"; // ª (same as before but with optional leading 0's)
echo "\u{9999}"; // 香

Closure call() Method


The new call() method for closures is used as a shorthand way of invoking a closure whilst binding an object scope to it. This creates more perfomant and compact code by removing the need to create an intermediate closure before invoking it.

class A {private $x = 1;}

// Pre PHP 7 code
$getXCB = function() {return $this->x;};
$getX = $getXCB->bindTo(new A, 'A'); // intermediate closure
echo $getX(); // 1

// PHP 7+ code
$getX = function() {return $this->x;};
echo $getX->call(new A); // 1

Filtered unserialize()


This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.

// converts all objects into __PHP_Incomplete_Class object
$data = unserialize($foo, ["allowed_classes" => false]);

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]]);

// default behaviour (same as omitting the second argument) that accepts all classes
$data = unserialize($foo, ["allowed_classes" => true]);

IntlChar Class


The new IntlChar class seeks to expose additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.

printf('%x', IntlChar::CODEPOINT_MAX); // 10ffff
echo IntlChar::charName('@'); // COMMERCIAL AT
var_dump(IntlChar::ispunct('!')); // bool(true)
In order to use this class, the Intl extension must be installed.

BC Breaks

Classes in the global namespace must not be called IntlChar.

Expectations


Expectations are backwards compatible enhancement to the older assert() function. They enable for zero-cost assertions in production code, and provide the ability to throw custom exceptions on error.

The assert() function's prototype is as follows:

void assert (mixed $expression [, mixed $message]);
As with the old API, if $expression is a string, then it will be evaluated. If the first argument is falsy, then the assertion fails. The second argument can either be a plain string (causing an AssertionError to be triggered), or a custom exception object containing an error message.

ini_set('assert.exception', 1);

class CustomError extends AssertionError {}

assert(false, new CustomError('Some error message'));
With this feature comes two PHP.ini settings (along with their default values):


  • zend.assertions = 1
  • assert.exception = 0

zend.assertions has three values:


  • 1 = generate and execute code (development mode)
  • 0 = generate code and jump around at it at runtime
  • -1 = don't generate any code (zero-cost, production mode)

assert.exception means that an exception is thrown when an assertion fails. This is switched off by default to remain compatible with the old assert() function.

Group use Declarations


This gives the ability to group multiple use declarations according to the parent namespace. This seeks to remove code verbosity when importing multiple classes, functions, or constants that come under the same namespace.

// Pre PHP 7 code
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Generator Return Expressions


This feature builds upon the generator functionality introduced into PHP 5.5. It enables for a return statement to be used within a generator to enable for a final expression to be returned (return by reference is not allowed). This value can be fetched using the new Generator::getReturn() method, which may only be used once the generator has finishing yielding values.

// IIFE syntax now possible - see the Uniform Variable Syntax subsection in the Changes section
$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})();

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

echo $gen->getReturn(), PHP_EOL;

// output:
// 1
// 2
// 3
Being able to explicitly return a final value from a generator is a handy ability to have. This is because it enables for a final value to be returned by a generator (from perhaps some form of coroutine computation) that can be specifically handled by the client code executing the generator. This is far simpler than forcing the client code to firstly check whether the final value has been yielded, and then if so, to handle that value specifically.

Generator Delegation


Generator delegation builds upon the ability of being able to return expressions from generators. It does this by using an new syntax of yield from <expr>, where can be any Traversable object or array. This will be advanced until no longer valid, and then execution will continue in the calling generator. This feature enables yield statements to be broken down into smaller operations, thereby promoting cleaner code that has greater reusability.

function gen()
{
    yield 1;
    yield 2;

    return yield from gen2();
}

function gen2()
{
    yield 3;

    return 4;
}

$gen = gen();

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

echo $gen->getReturn();

// output
// 1
// 2
// 3
// 4

Integer Division with intdiv()


The intdiv() function has been introduced to handle division where an integer is to be returned.

var_dump(intdiv(10, 3)); // int(3)

session_start() Options


This feature gives the ability to pass in an array of options to the session_start() function. This is used to set session-based php.ini options:

session_start(['cache_limiter' => 'private']); // sets the session.cache_limiter option to private
This feature also introduces a new php.ini setting (session.lazy_write) that is, by default, set to true and means that session data is only rewritten if it changes.

preg_replace_callback_array() Function


This new function enables code to be written more cleanly when using the preg_replace_callback() function. Prior to PHP 7, callbacks that needed to be executed per regular expression required the callback function (second parameter of preg_replace_callback()) to be polluted with lots of branching (a hacky method at best).

Now, callbacks can be registered to each regular expression using an associative array, where the key is a regular expression and the value is a callback.

Function Signature:

string preg_replace_callback_array(array $regexesAndCallbacks, string $input);
$tokenStream = []; // [tokenName, lexeme] pairs

$input = <<<'end'
$a = 3; // variable initialisation
end;

// Pre PHP 7 code
preg_replace_callback(
    [
        '~\$[a-z_][a-z\d_]*~i',
        '~=~',
        '~[\d]+~',
        '~;~',
        '~//.*~'
    ],
    function ($match) use (&$tokenStream) {
        if (strpos($match[0], '$') === 0) {
            $tokenStream[] = ['T_VARIABLE', $match[0]];
        } elseif (strpos($match[0], '=') === 0) {
            $tokenStream[] = ['T_ASSIGN', $match[0]];
        } elseif (ctype_digit($match[0])) {
            $tokenStream[] = ['T_NUM', $match[0]];
        } elseif (strpos($match[0], ';') === 0) {
            $tokenStream[] = ['T_TERMINATE_STMT', $match[0]];
        } elseif (strpos($match[0], '//') === 0) {
            $tokenStream[] = ['T_COMMENT', $match[0]];
        }
    },
    $input
);

// PHP 7+ code
preg_replace_callback_array(
    [
        '~\$[a-z_][a-z\d_]*~i' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_VARIABLE', $match[0]];
        },
        '~=~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_ASSIGN', $match[0]];
        },
        '~[\d]+~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_NUM', $match[0]];
        },
        '~;~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_TERMINATE_STMT', $match[0]];
        },
        '~//.*~' => function ($match) use (&$tokenStream) {
            $tokenStream[] = ['T_COMMENT', $match[0]];
        }
    ],
    $input
);

CSPRNG Functions


This feature introduces two new functions for generating cryptographically secure integers and strings. They expose simple APIs and are platform-independent.

Function signatures:

string random_bytes(int length);
int random_int(int min, int max);
Both functions will emit an Error exception if a source of sufficient randomness cannot be found.

Support for Array Constants in define()


The ability to define array constants was introduced in PHP 5.6 using the const keyword. This ability has now been applied to the define() function too:

define('ALLOWED_IMAGE_EXTENSIONS', ['jpg', 'jpeg', 'gif', 'png']);

Reflection Additions


Two new reflection classes have been introduced in PHP 7. The first is ReflectionGenerator, which is used for introspection on generators:

class ReflectionGenerator
{
    public __construct(Generator $gen)
    public array getTrace($options = DEBUG_BACKTRACE_PROVIDE_OBJECT)
    public int getExecutingLine(void)
    public string getExecutingFile(void)
    public ReflectionFunctionAbstract getFunction(void)
    public Object getThis(void)
    public Generator getExecutingGenerator(void)
}
The second is ReflectionType to better support the scalar and return type declaration features:

class ReflectionType
{
    public bool allowsNull(void)
    public bool isBuiltin(void)
    public string __toString(void)
}
Also, two new methods have been introduced into ReflectionParameter:

class ReflectionParameter
{
    // ...
    public bool hasType(void)
    public ReflectionType getType(void)
}
As well as two new methods in ReflectionFunctionAbstract:

class ReflectionFunctionAbstract
{
    // ...
    public bool hasReturnType(void)
    public ReflectionType getReturnType(void)

}

These were the new features in PHP 7.

Wednesday, May 3, 2017

Top Laravel Interview Questions with Answers

Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax. Now a days Laravel is very popular PHP framework so mostly companies works on this framework. Here we are listing top Laravel interview questions with answers.



1. What is Laravel?
Laravel is a open-source PHP framework developed by Taylor Otwell used for Developing the websites. Laravel helps you create applications using simple, expressive syntax.

2. What are Advantages of Laravel?

  • Easy and consistent syntax
  • Set-up process is easy
  • customization process is easy
  • code is always regimented with Laravel
3. Explain about Laravel Project?
Laravel is one of the most popular PHP frameworks used for Web Development.
This framework is with expressive, elegant syntax.
It is based on model–view–controller (MVC) architectural pattern.

4. What are the feature of Laravel 5.4?
  • Introducing Laravel Dusk
  • Introducing Laravel Mix 
  • New Markdown Mail in Laravel 5.4 
  • Slots and Components in Laravel 5.4
  • Real-time (automatic) Facades in Laravel 5.4
  • TrimStrings and ConvertEmptyStringsToNull middleware in Laravel 5.4
  • JSON localization files in Laravel 5.4
  • Binding method calls in the service container in Laravel 5.4 
  • The --model flag for creating better resourceful controllers in Laravel 5.4
  • Laravel Collections' updates--higher order messaging and new methods--in Laravel 5.4 
5. Compare Laravel with Codeigniter?
        Laravel                                                                                        Codeigniter
Laravel is a framework with expressive, CodeIgniter is a powerful PHP                       elegant syntax                                                                    framework
Development is enjoyable, creative                                 Simple and elegant toolkit to create full-         experience                                                                         featured web applications.
Laravel is built for latest version of PHP                         Codeigniter is an older more mature                                                                                                         framework
It is more object oriented compared                                 It is less object oriented compared to               to CodeIgniter.                                                                  Laravel.
Laravel community is still small, but it is                        Codeigniter community is large.
growing very fast.

6. What are Bundles,Reverse Routing and The IoC container ?

Bundles: These are small functionality which you may download to add to your web application.
Reverse Routing: This allows you to change your routes and application will update all of the relevant links as per this link.
IoC container: It gives you Control gives you a method for generating new objects and optionally instantiating and referencing singletons.

Also Read: PHP Interview Questions with Answers

7. How to set Database connection in Laravel?
Database configuration file path is : config/database.php
Following are sample of database file

[code]  'mysql' => [
    'read' => [
        'host' => 'localhost',
    ],
    'write' => [
        'host' => 'localhost'
    ],
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
], [/code]

8. How to enable the Query Logging?
[code] DB::connection()->enableQueryLog();[/code]

9. How to use select query in Laravel?
[code] $users = DB::select('select * from users where city_id = ?', 10);
if(!empty($users)){
    foreach($users as $user){

    }
} [/code]

9. How to use Insert Statement in Laravel?
[code] DB::insert('insert into users (id, name, city_id) values (?, ?)', [1, 'Web technology',10]); [/code]

10. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]); [/code]

11. How to use Update Statement in Laravel?
[code]  DB::update('update users set city_id = 10 where id = ?', [1015]);[/code]

12. How to use delete Statement in Laravel?
[code] DB::delete('delete from  users where id = ?', [1015]); [/code]

13. Does Laravel support caching?
Yes, Its provides.

Also Read: Top Zend Framework Interview Questions with Answers

14. I've already created a database table that I want to use with Laravel's ORM. How would I setup a class to do that?
Laravel's ORM is called Eloquent. There are two main ways to go about doing this. The first one would be to physically write a class:
[code] <?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'students';
}[/code]

And the second one would be to use the artisan CLI, which generates a class:
[code] php artisan make:model students [/code]

15. Laravel comes with a PHP CLI called artisan. What is your favorite artisan command?
There are so many things that the CLI does out of the box. Even if they don't have a favorite command, they should be able to explain what some of them do. Here's a sample of available top-level commands:
Available commands:
  •   clear-compiled      Remove the compiled class file
  •   down                Put the application into maintenance mode
  •   env                 Display the current framework environment
  •   help                Displays help for a command
  •   inspire             Display an inspiring quote
  •   list                Lists commands
  •   migrate             Run the database migrations
  •   optimize            Optimize the framework for better performance
  •   serve               Serve the application on the PHP development server
  •   tinker              Interact with your application
  •   up                  Bring the application out of maintenance mode
16. Laravel 5 has built in CSRF protection on every route. How would I go about turning that off?
  Hopefully they mention that CSRF protection is important, but since we're asking them to turn it off they might not mention it which is OK. You'd easily turn it off by going into Kernel.php and removing it from the middleware stack that is ran on every route.

This is also a good place to ask about middleware in general and make sure they both understand what middleware is and why it's important.

17. List out some benefits of Laravel over other Php frameworks.
  • Setup and customization process is  easy and fast as compared to others.
  • Inbuilt Authentication System.
  • Supports multiple file systems
  • Pre-loaded packages like Laravel Socialite, Laravel cashier, Laravel elixir,Passport,Laravel Scout.
  • Eloquent ORM (Object Relation Mapping) with PHP active record implementation. 
  • Built in command line tool “Artisan” for creating a code skeleton ,database structure and build their migration.
Also Read: WordPress Interview Questions And Answers

18. What is composer ?
Composer is PHP dependency manager used for installing dependencies of PHP applications.

19. How to install laravel via composer ?

 composer create-project laravel/laravel your-project-name version

 20. How to check laravel current version ?
 You can check the current version of your Laravel installation using the --version option of artisan command Usages:
 [code] php artisan --version [/code]

21. What is php artisan. List out some artisan command ?

PHP artisan is the command line interface/tool included with Laravel. It provides a number of helpful commands that can help you while you build your application easily. Here are the list of some artisian command:
  • php artisan list
  • php artisan help
  • php artisan tinker
  • php artisan make
  • php artisan --versian
  • php artisan make modal modal_name
  • php artisan make controller controller_name 
22. Explain Events in laravel ?

An event is an incident or occurrence detected and handled by the program.Laravel event provides a simple observer implementation,that allow us  to subscribe and listen for events in our application.
Below are some events examples in laravel :
A new user has registered
A new comment is posted
User login/logout
New product is added.

23. How to enable query log in laravel?

Use the enableQueryLog method:
DB::connection()->enableQueryLog();
You can get array of the executed queries by using getQueryLog method:
$queries = DB::getQueryLog();

Also Read: Most Popular Codeigniter Interview Questions with Answers

24. How to turn off CRSF protection for a route in Laravel?

In "app/Http/Middleware/VerifyCsrfToken.php"
 //add an array of Routes to skip CSRF check
  private $exceptUrls = ['controller/route1', 'controller/route2'];
 //modify this function

[code]public function handle($request, Closure $next) {
 //add this condition foreach($this->exceptUrls as $route) {
 if ($request->is($route)) {
  return $next($request);
 }
}
return parent::handle($request, $next);
}[/code]

25. How can you get users IP address  in Laravel ?

[code] public function getUserIp(Request $request){
          // Getting ip address of remote user

            return $user_ip_address=$request->ip();
}[/code]

26. How to use custom table in Laravel Modal We can use custom table in laravel by overriding protected $table property of Eloquent. Below is sample uses

[code] class User extends Eloquent{
 protected $table="my_user_table";

}[/code]

27. How to define Fillable Attribute in Laravel Modal ?
You can define fillable attribute by overiding the fillable property of Laravel Eloquent. Here is sample uses

[code] Class User extends Eloquent{

protected $fillable =array('id','first_name','last_name','age');


}[/code]

28. In which directory controllers are located in Laravel ?

We kept all controllers in
app/http/Controllers directory

29. What does PHP compact function do ?
PHP compact function takes each key and tries to find a variable with that same name.If variable is found , them it builds an associative array.

30. Define ORM ?
Object-relational Mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.

Also Read: Apache Solr Interview Questions and Answers

31. How to create a record in Laravel using eloquent? 

To create a new record in the database using laravel Eloquent, simply create a new model instance, set attributes on the model, then call the save method: Here is sample Usage

[code] public function saveProduct(Request $request )
 $product = new product;
 $product->name = $request->name;
 $product->description = $request->name;
 $product->save(); [/code]

 32. What is the purpose of the Eloquent cursor() method in laravel?

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage. Example Usage

[code] foreach (Product::where('name', 'bar')->cursor() as $flight) { //do some stuff } [/code]

33. How to get Logged in user info in laravel ?

Auth::User() function is used to get Logged in user info in laravel. Usage:

[code] if(Auth::check()){

$loggedIn_user=Auth::User();
dd($loggedIn_user);

} [/code]


34. What are Closures in laravel ?
Closures is an anonymous function that can be assigned to a variable or passed to another function as an argument.A Closures can access variables outside the scope that it was created.


Tuesday, May 2, 2017

Most Popular Codeigniter Interview Questions with Answers

CodeIgniter is an open-source software rapid development web framework, for use in building dynamic web sites with PHP. CodeIgniter is popular model–view–controller (MVC) development pattern. CodeIgniter is most often noted for its speed when compared to other PHP frameworks. Today mostly web development happens in CodeIgniter framework. In PHP interview a lot of questions are asked from CodeIgniter. Here we are listing most popular CodeIgniter Interview Questions with Answers.


1. What is Codeigniter?

Codeigniter is the most popular open source PHP framework. It is very simple and lightweight. It can be used to develop any kind of web project from small website to large scale of application.

2. What are the most prominent features of CodeIgniter?

A list of most prominent features of CodeIgniter:

It is an open source framework and free to use.
It is extremely light weighted.
It is based on Model View Controller (MVC) pattern.
It has full featured database classes and support for several platforms.
It is extensible. You can easily extend system by using your own libraries, helpers etc.
Excellent documentation.
Security and XSS Filtering
File uploading, session management, pagination, data encryption
Flexible URI Routing
Zip encoding class
Error logging
Full page caching
Localization

3. Explain the folder structure of CodeIgniter.

If you download and unzip CodeIgniter, you will get the following file structure/folder structure:


Application     
cache
Config
Controllers
core
errors
helpers
hooks
language
libraries
logs
models
thirdparty
views

system

core
database
fonts
helpers
language
libraries

4. How to access config variable in codeigniter? 

[code] $this->config->item('variable name'); [/code]

5. How to unset session in codeigniter?

[code] $this->session->unsetuserdata('somename');  [/code]

6. How do you get last insert id in codeigniter? 

 [code]  $this->db->insertid(); [/code]


7. Why use Hooks in Codeigniter

Hooks are the special feature of Codeigniter that allows to change the inner functionality of framework without making any change in core files of framework. The Hooks are defined in application/config/hooks.php.

8. What are different types of hook points in CodeIgniter?

A list of different types of hook points in CodeIgniter:

post_controller_constructor
pre_controller
post_sytem
pre_system
cache_override
display_override
post_controller

9. How can you load a view in CodeIgniter?

View can't be accessed directly. It is always loaded in the controller file. Following function is used to load a view page:

[code]  $this->load->view('page_name');  [/code]


10. What is routing in Codeigniter?

Instead of accessing files directly from browser, Routing enables to serve files differently. Routing is an important part of Codeigniter that enables to customize default URL pattern according to requirement to use your own and it redirect automatically to matched URL pattern by specified controller and function.

11. How to load Model in CodeIgniter?

Models are PHP classes that are designed to work with information in your database. In CodeIgniter, Model classes are stored in your application/models/ folder. The models will typically be loaded and called from within your controller functions. To load a model you will use the following function:
[code] $this->load->model('Model_name'); [/code]

12. What are the Helpers in CodeIgniter?

The Helpers are the group of functions in a specific category that helps to perform particular functions. There are many helpers in CodeIgniter that you can use according to your requirement. The major CodeIgniter helpers are URL Helpers that assist in creating link, Form Helpers that help you create form elements, Text Helpers to perform various text formatting routines, Cookie Helpers to set and read cookies, File Helpers to help you deal with files etc.

13. List out different types of hook point in Codeigniter?

Different types of hook point in Codeigniter includes
post_controller_constructor
pre_controller
post_sytem
pre_system
cache_override
display_override
post_controller

14. Mention what are the security parameter for XSS in CodeIgniter?

Codeigniter has got a cross-site scripting hack prevention filter. This filter either runs automatically or you can run it as per item basis, to filter all POST and COOKIE data that come across.  The XSS filter will target the commonly used methods to trigger JavaScript or other types of code that attempt to hijack cookies or other malicious activity. If it detects any suspicious thing or anything disallowed is encountered, it will convert the data to character entities.

15. Explain how you can link images/CSS/JavaScript from a view in code igniter?

In HTML, there is no Codeigniter way, as such it is a PHP server side framework. Just use an absolute path to your resources to link images/CSS/JavaScript from a view in CodeIgniter
/css/styles.css

/js/query.php

/img/news/235.gpg

16. Explain what is inhibitor in CodeIgniter?

For CodeIgniter, inhibitor is an error handler class, using the native PHP functions like set_exception_handler, set_error_handler, register_shutdown_function to handle parse errors, exceptions, and fatal errors.

17. Mention what is the default URL pattern used in Codeigniter framework?

Codeigniter framework URL has four main components in default URL pattern.  First we have the server name and next we have the controller class name followed by controller function name and function parameters at the end. Codeigniter can be accessed using the URL helper. For example http://servername/controllerName/controllerFunction/parameter1/parameter2.

18. Explain how you can extend the class in Codeigniter?

To extend the native input class in CodeIgniter, you have to build a file named application/core/MY_Input.php and declare your class with
[code] Class MY_Input extends CI_Input {

} [/code]

19.How can you load multiple helper files?

To load multiple helper files, specify them in an array,
[code] $this->load->helper(  
array('helper1', 'helper2', 'helper3')  
);  [/code]

20. Explain how you can prevent CodeIgniter from CSRF?

There are several ways to protect CodeIgniter from CSRF, one way of doing is to use a hidden field in each form on the website.  This hidden field is referred as CSRF token; it is nothing but a random value that alters with each HTTP request sent. As soon as it is inserted in the website forms, it gets saved in the user’s session as well.  So, when the form is submitted by the users, the website checks whether it is the same as the one saved in the session. If it is same then, the request is legitimate.

21. Explain how you can enable CSRF (Cross Site Request Forgery) in CodeIgniter?

You can activate CSRF (Cross Site Request Forgery) protection in CodeIgniter by operating your application/config/config.php file and setting it to
[code] $config [ 'csrf_protection'] = TRUE; [/code]
If you avail the form helper, the form_open() function will insert a hidden csrf field in your forms automatically


22. What are CodeIgniter drivers?

These are special type of library that has a parent class and many child classes. These child classes have access to the parent class, but not to their siblings. Drivers are found in system/libraries folder.

23. How to initialize a driver in CodeIgniter?

To initialize a driver, write the following syntax,
[code] $this->load->driver('class_name');  [/code]