PHP 7 tutorial | php tutorial for beginners

Operator in PHP 7:

comparison between Interger, float and string with spaceship operator in PHP 7. we can use the symbol “<=>”.

Example:

<?php

//integer comparison

print( 1 <=> 1);print("<br/>");

print( 1 <=> 2);print("<br/>");

print( 2 <=> 1);print("<br/>");

print("<br/>");

//float comparison

print( 1.5 <=> 1.5);print("<br/>");

print( 1.5 <=> 2.5);print("<br/>");

print( 2.5 <=> 1.5);print("<br/>");

print("<br/>");

//string comparison

print( "a" <=> "a");print("<br/>");

print( "a" <=> "b");print("<br/>");

print( "b" <=> "a");print("<br/>");

?>

The result is:

Define a constant Arrays in PHP 7:

we can define a constant arrays in PHP 7 by using define() function.

Example:

<?php

//define a array using define function

define('movies', [

'TV Show',

'Actor',

'Actress'

]);

print(movies[2]);

?>

The result is:

Actress

 

Anonymous Classes in PHP 7

we can define anonymous classes by using new class. It can be used in stade of full class definition.

Example:

<?php

interface Message {

public function sms(string $msg);

}

 

class Application {

private $x;

//implement Message interface

public function getLogger(): Message {

return $this->x;

}

 

public function setLogger(Message $x) {

$this->x = $x;

}

}

 

$app = new Application;

//Anonymous class

$app->setLogger(new class implements Message {

public function sms(string $msg) {

print($msg);

}

});

 

$app->getLogger()->sms("Hellow Anonymous, This is new class");

?>

The result is:

Hellow Anonymous, This is new class

 

Closure::call() i n PHP 7

Closure::call() is a method used as a shorthand way to link an object scope to a closure and Call it (like bindTo in PHP 5.6).

Example:

<?php

// Pre PHP 7*******************************

class close {

private $a = "Hellow World! <br>";

}

 

// Define a closure Pre PHP 7 code

$getValue = function() {

return $this->a;

};

 

// Bind a clousure

$value = $getValue->bindTo(new close, 'close');

 

print($value());

//*********************************

 

//in PHP 7 now

 

class closePHP7 {

private $x = "Closure call in PHP 7 <br>";

}

 

// PHP 7+ code, Define

$value = function() {

return $this->x;

};

// display message

print($value->call(new closePHP7));

 

?>

The result is :

Hellow World!
Closure call in PHP 7