Showing posts with label php7. Show all posts
Showing posts with label php7. Show all posts

Saturday 30 May 2020

PHP 7 Scalar type declarations and return type declarations

PHP 7  Scalar type declarations and return type declarations

What is a Scalar type declarations?
Allowing/Not-Allowing datatype declaration in functions is known as Scalar type declarations.


Question: What are different types of Scalar type declarations?
1) Coercive Mode (default)
2) Strict Mode


What are different type of data-type can be used in Scalar type declarations?
  1. int
  2. float
  3. bool
  4. string
  5. interfaces
  6. array
  7. callable



Question: Give the examples of Scalar type declarations with Coercive Mode (default)
Example 1
$a=1; // integer
$b=2; //integer
function FunctionName1(int $a, int $b){
return $a + $b;
}
echo FunctionName1($a, $b); //3


Example 2
   function sum(int ...$ints) {
      return array_sum($ints);
   }

   print(sum(3, '2', 5.1)); //10


Example 3
function FunctionName3(int $a, int $b){
return $a * $b;
}

echo FunctionName3('hello', 10); //PHP Fatal error: Uncaught TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given.


Example 4
$a='1One'; 
$b=2; //integer
function FunctionName3(int $a, int $b){
return $a + $b;
}
echo FunctionName3($a, $b);//RESULT: PHP Notice: A non well formed numeric value encountered on line 5


Question: Give the examples of Scalar type declarations with STRICT MODE?
Example 1
declare(strict_types=1); 

$a=1; // integer
$b=2; //integer
function phpFunction (int $a, int $b){
return $a + $b;
}

echo phpFunction1($a, $b);//3

Example 2
declare(strict_types=1); 

$a='1'; // String
$b=2; //integer
function phpFunction1 (int $a, int $b){
return $a + $b;
}

echo phpFunction1($a, $b);//Fatal error: Uncaught TypeError: Argument 1 passed to phpFunction1() must be of the type int, string given


Question: Give the examples of Return type declarations with STRICT MODE?
Example 1
$a='10'; //  string
$b=2; // integer
function phpFunctionReturn ($a, $b) : int  {
return $a * $b;
}
echo phpFunctionReturn ($a, $b);


Example 2
declare(strict_types=1); 
$a='10'; //  string
$b=2; // integer
function phpFunctionReturn ($a, $b) : string  {
return $a * $b;
}
echo phpFunctionReturn ($a, $b);//PHP Fatal error:  Uncaught TypeError: Return value of phpFunctionReturn() must be of the type string, integer returned in /home/cg/root/7035270/main.php:6




Thursday 12 September 2019

New PHP 7 Feature List

New PHP 7 Feature List

Question: Why we should use PHP 7 as compare to PHP5?
  1. Improved performance. Its twice as fast as compare to PHP 5.
  2. Lower Memory Consumption.
  3. Scalar type declarations.
  4. Return and Scalar Type Declarations.
  5. Consistent 64-bit support
  6. Many fatal errors converted to Exceptions
  7. Secure random number generator.
  8. Various old and unsupported SAPIs and extensions are removed from the latest version
  9. NULL coalescing operator removed
  10. Anonymous Classes Added.
  11. Zero cost asserts
  12. Use of  new Zend Engine 3.0



Question: What is PHPNG?
PHPNG branch has been merged into master and has been used as the base for PHP 7.0.
PHPNG target is improve the performance and memory usage efficiency of PHP.


Question: What is a PHP parser?
PHP parser is a software which understand your coding and convert to computer language So that it can be executed & gives a output in HTML.


Question: What is a Scalar type declarations?
Allowing/prohibited datatype declaration in functions know for Scalar type declarations.
There are two options in Scalar type declarations
1) Coercive Mode (default)
2) Strict Mode
function sum(int ...$ints) {
      return array_sum($ints);
   }
   print(sum(2, '20', 4.2)); //26.2



Question: How to use return type declarations?
 function returnIntValue(int $value): int {
      return $value;
   }
   print(returnIntValue(5));



Question: What is spaceship operator?
It is Operator which is used to compare two expressions.
It return -1, 0 or 1.
print( 1 <=> 1); //0
print( 1 <=> 2); //-1
print( 2 <=> 1); //1




Question: Can define accept an array?
Yes, It can. For Example:
define('CLIENTS', [
    'client 1',
    'client 2',
    'client 3'
]);



Question: What is use of Closure::call() in PHP7?
It is used to temporarily bind an object scope to a closure and invoke it.
For Example:
 class A {
      private $x = 1;
   }
   $value = function() {
      return $this->x;
   };
   print($value->call(new A));



Question: How to import import Classes using single use statement?
Before PHP 7
use com\mytestclass\ClassA;
use com\mytestclass\ClassB;
use com\mytestclass\ClassC as C;

In PHP 7
 use com\mytestclass\{ClassA, ClassB, ClassC as C};



Question: What are Deprecated features in PHP7?
Following are deprecated feature in PHP7.
  1. Old Style Constructure.
     class A {
          function A() {
             print('Deprecated');
          }
       }
    
  2. Static calls to non-static methods.
    class A {
          function b() {
             print('Deprecated');
          }
       }
       A::b();
    
    
  3. password_hash() salt



Question: What extension are removed ?
  1. ereg
  2. mssql
  3. mysql
  4. sybase_ct



Question: From where I can download PHP7?
http://php.net/downloads.php


Question: How to setup PHP7 with WampServer?
http://www.wampserver.com/en/


Question: What is Class Abstraction?
1. Classes defined as abstract may not be instantiated.
2. Class that contains at least one abstract method must also be abstract.
3. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child.
4. if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.



Question: Tell me something about Interface?
We use "interface" keyword to create class.
All methods declared in an interface must be public.
To implement an interface, the implements operator is used.
We can include multiple interface while implementing



Question: What are Traits? Give example
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
We can't create instance of a traits

We can create Traits as below:-
    trait Hello {
        public function sayHello() {
            echo 'Hello ';
        }
    }   


We can use multiple traits using comma like below
use Hello, World;
When two traits have same function, it would conflict but we can fix using insteadof like below
A::bigTalk insteadof B;
We can set the visibility of function using "as" like below
use HelloWorld { sayHello as protected; }

We can use one trait from another using "use"
we can also define abstract,static, data members, method




Question: What is Overloading?
Overloading in PHP provides means to dynamically create properties and methods.
These dynamic entities are processed via magic methods one can establish in a class for various action types.
__get(), 
__set(), 
__isset() 
__unset() 
__call()
__callStatic()


Monday 6 May 2019

Difference between a lambda function and a closure (in PHP)

Difference between a lambda function and a closure (in PHP)

Question: Difference between a lambda function and a closure (in PHP)?
Lambda function is a function that assigned to a variable or passed to another function as parameter.

Example:
$greeting = function () {
  return "Hello world";
}
echo $greeting();//Hello world



A closure is a lambda function, but a lambda function is not a closure unless you specify the use keyword.

Example:

$user = "Rony";
// Create a Closure
$greeting = function() use ($user) {
  echo "Hello $user";
};
// Greet the user
$greeting();//Hello Rony


Wednesday 13 February 2019

PHP 7 interview Questions and Answers

PHP 7 interview Questions and Answers

Question: What is class Constants?
You can define constant as string OR expression within the class. but you can not define class as variable, or function.


Question: When will Autoloading function will be called once defined?
a) spl_autoload_register (autoload) will called when create object of class.
b) spl_autoload_register will called when extend by any class (using extends).
c) spl_autoload_register will called when implements an interface (using implements ).


Question: What is visibility? What are different type of visibility in class?
visibility means setting the access level of data member and member function.
Class methods must be declare as public, protected or private.
You can also declare with var which means public


Question: What is Static Keyword?
Declaring class property or methods as static makes them accessible without needing an instantiation of the class.
$this is not available inside the function.


Question: Tell me about Abstraction in PHP?
  1. Classes defined as abstract may not be instantiated.
  2. Class that contains at least one abstract method must also be abstract.
  3. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child.
  4. if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private.



Question: Tell me about Interface in PHP?
  1. We use "interface" keyword to create class.
  2. All methods declared in an interface must be public.
  3. To implement an interface, the implements operator is used.
  4. We can include multiple interface while implementing



Question: Tell me about Traits in PHP?
Traits are a mechanism for code reuse in single inheritance languages such as PHP.
We can't create instance of a traits
We can create Traits as below
    
trait Hello {
        public function sayHello() {
            echo 'Hello ';
        }
    }
We can use multiple traits using comma like below
 use Hello, World;
When two traits have same function, it would conflict but we can fix using insteadof like below
A::bigTalk insteadof B;
We can set the visibility of function using "as" like below
use HelloWorld { sayHello as protected; }
We can use one trait from another using "use"
we can also define abstract,static, data members, method


Question: Tell me about Anonymous classes?
We can create a class without specifing the class-name. Following are example
$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});


Question: What is Overloading in PHP?
Overloading in PHP provides means to dynamically create properties and methods.
These dynamic entities are processed via magic methods one can establish in a class for various action types.
example of magic functions __get(), __set(), __isset(), __unset(), __call(),__callStatic() etc


Friday 1 February 2019

PHP 7 New Features

PHP 7 New Features

Question: What are main features of PHP 7?
  1. Lower Memory Consumption
  2. Improved performance as now using Zend Engine 3.0
  3. Consistent 64-bit support
  4. Scalar type declarations
  5. Return type declarations
  6. define() updates: Now you can add array.
  7. unserialize updates: Provide better security when unserializing objects on untrusted data
  8. Anonymous classes can be created
  9. Null coalescing operator (??) have been added
    Namespaces declaration like use some\namespace\{ClassA, ClassB, ClassC as C};
  10. Many fatal errors converted to Exceptions
  11. Secure random number generator
  12. session_start will accept an array.
  13. Spaceship operator
  14. list() function updates



Question: What is null coalescing operator?
null coalescing operator (??) has been introduced in PHP7.
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
print($username);



Question: What are Scalar type declarations?
Scalar type declarations has two type of options.
  1. coercive - coercive is default mode and need not to be specified.
  2. strict - strict mode has to explicitly hinted.



Question: What is Namespaces?
Namespaces are a way of encapsulating items. we can use two more different classes into one Namespaces.


Question: What is purpose of Namespaces?
1) To fixed the name collisions between your code and internal PHP classes/functions/constants or third-party classes/functions/constants.
2) Ability to shorten for Extra_Long_Names, improving readability of source code.



Question: Explain about Namespaces in PHP7?
  1. Namespace must be the first statement in the PHP Script.
  2. We can define Sub-Namespace also
  3. Defining multiple namespaces in same file with/without using bracketed syntax (Multiple declaration is not Recommended)
  4. We can access the Global method of namespaces using \
    namespace A\B\C;
            function strlen($string){
                return \strlen($string).'--arun';
            }
        echo strlen('imarun');
  5. we can use __NAMESPACE__ for getting the current namespace name
  6. We can use Alias for namespace as below
    use mynamespace\car as mycar;
  7. import multiple namespaces in single line
    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};  
  8. Using namespaces: fallback to global function/constant
    a) An unqualified class name resolve to current namespace
    b) An unqualified function name resolve to current namespace
    c) An unqualified constant name resolve to Global namespace



Question: What is Class Constants?
Class Constants: You can define constant as string OR expression. but you can not define as variable, or function.


Question: When autoloading classes loads automatic?
a) Autoload when create object.
b) Autoload when include an another (using extends)
c) Autoload when include an interface (using implements )
d) we Can add exception in spl_autoload_register


Question: What is Visibility?
Class methods must be declare as public, protected or private.
You can also declare with var which means public


Question: What are Static Keyword?
Declaring class property or methods as static makes them accessible without needing an instantiation of the class.
$this is not available inside the function.