Category Archives: PHP

Understanding PHP Generator With Example

phpgen

Overview Of Generators:

Generator does not returns a value but generates a sequence of values. It is a normal function that instead of returning a value yields as many values as needed to get a desired result.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate.

A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.

The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.

A Simple Generator:

<?php

function gen_one_to_ten(){

for($i=1;$i<=10;$i++){

yield$i;

}

}

$gen=gen_one_to_ten();

foreach($gen as $value){

echo"$value\t";

}

?>

Fibonacci Generator Example:

<?php

function fib($n)

{

$cur=1;

$prev=0;

for ($i=0; $i<$n; $i++) {

yield$cur;

$temp=$cur;

$cur=$prev+$cur;

$prev=$temp;

}

}

$fibs = fib(9);

foreach ($fibs as $fib) {

echo" ".$fib;

}

// prints: 1 1 2 3 5 8 13 21 34
?>

 

Advertisements

PHP7 Arithmetic Operators

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.
+   Addition     $x + $y     Sum of $x and $y
–   Subtraction     $x – $y     Difference of $x and $y
*   Multiplication  $x * $y     Product of $x and $y
/   Division     $x / $y     Quotient of $x and $y
%   Modulus      $x % $y     Remainder of $x divided by $y
**  Exponentiation  $x ** $y    Result of raising $x to the $y’th power

PHP Increment / Decrement Operators

The PHP increment operators are used to increment a variable’s value.
The PHP decrement operators are used to decrement a variable’s value.
++$x    Pre-increment   Increments $x by one, then returns $x
$x++    Post-increment  Returns $x, then increments $x by one
–$x    Pre-decrement   Decrements $x by one, then returns $x
$x–    Post-decrement  Returns $x, then decrements $x by one
<?php

$x=20;

$y=15;

//addition

$add=$x+$y;

echo $add.'
'; //subtraction $sub=$x-$y; echo $sub.'
'; //multiplication $mult=$x*$y; echo $mult.'
'; //division $div=$x/$y; echo $div.'
'; //modulus $mod=$x%$y; echo $mod.'
'; //Exponentiation $exp=$x**$y; echo $exp.'
'; $num=20; $num2=10; //Pre-increment echo ++$num.'
'; //post-increment echo $num++.'
'; echo $num.'
'; //Pre-decrement echo --$num2.'
'; //Post-decrement echo $num2--.'
'; echo $num2.'
'; ?>

Download File

PHP 7 Comparison Operator

PHP Comparison Operators
The PHP comparison operators are used to compare two values (number or string):
==       Equal    $num1 == $num2    Returns true if $num1 is equal to $num2
===    Identical    $num1 === $num2   Returns true if $num1 is equal to $num2, and they are of the same type
!=       Not equal    $num1 != $num2    Returns true if $num1 is not equal to $num2
<>       Not equal    $num1 <> $num2    Returns true if $num1 is not equal to $num2
!==     Not identical    $num1 !== $num2   Returns true if $num1 is not equal to $num2, or they are not of the    same type
>         Greater than     $num1 > $num2     Returns true if $num1 is greater than $num2
<        Less than    $num1 < $num2     Returns true if $num1 is less than $num2
>=     Greater than or equal to $num1 >= $num2   Returns true if $num2 is greater than or equal to $num2
<=     Less than or equal to    $num1<= $num2    Returns true if $num2 is less than or equal to $num2
<?php

$num1=10;

$num2=7;

$numStr='10';

//always true

if(true){

echo'I am always true'.'<br>';

}

//always false

if(false){

echo'I am true'.'<br>';

}else{

echo'I am always false'.'<br>';

}

//return true if $num1 is equal to $numStr

if($num1==$numStr){

echo'we are same'.'<br>';

}

//return true if $num1 is identical to $numStr and same type

if($num1===$numStr){

echo'we are identical'.'<br>';

}else{

echo 'We are not identical'.'<br>';

}

//return true if $num1 is not equal to $num2

if($num1!=$num2){

echo'we are not same'.'<br>';

}

// same as !=

if($num1<>$num2){

echo'we are not same'.'<br>';

}

if($num1!==$numStr){

echo'we are not identical'.'<br>';

}

//return true if $num1 is greater than $num2

if($num1>$num2){

echo$num1.' is greater than '.$num2.'<br>';

}else{

echo$num2.' is greater than '.$num1.'<br>';

}

//return true if $num1 is less than $num2

if($num1<$num2){

echo$num1.' is less than '.$num2.'<br>';

}else{

echo$num2.' is less than '.$num1.'<br>';

}

//return true if $num1 is greater than or equal to $num2

if($num1>=$num2){

echo$num1.' is greater than or equal to'.$num2.'<br>';

}else{

echo$num2.' is greater than or equal to'.$num1.'<br>';

}

//return true if $num1 is less than or equal to $num2

if($num1<$num2){

echo$num1.' is less than or equal to '.$num2.'<br>';

}else{

echo$num2.' is less than or equal to '.$num1.'<br>';

}

?>

Download file

PHP Class Attribute With Example

An attribute is known as data members and is used to hold data of a class. The data that it holds are specific to the nature of the class in which it has been defined. For example, a Book class would hold data related to a book, an Publisher class would hold data related a an publisher. Properties can accept values like strings, integers, and booleans (true/false values), like any other variable. Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property. Attributes can either be public, private or protected – the default being public. These are called Access Specifiers.
Example Code:

class Book {
private $book_name, $author_name;
private $price = 0;
public function getData($book_name, $author_name) {
$this->book_name = $book_name;
$this->author_name = $author_name;
}public function printData() {
echo 'Book Name:'.$this->book_name . 'Author Name:' . $this->author_name;
}
}
$c1 = new Book();

In the above example $book_name, $author_name and $price are data members or attributes of the class Book. Of these attributes, $price has a default value of zero assigned to it. This means that when an object of the Book class has been created, $book_name and $author_name will be blank whereas; $price will be initialized with default value of zero.

php-magic-constants
c-program-to-find-simple-interest

Object Oriented Programming in PHP

php-7-up-and-runningObject-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods.It organizes the data and structure of an application. Here in this tutorial, you will learn about basic OOP concept and also how data and functions can be represented as reusable objects that are cut down on code and time.

Object Oriented Programming Concepts in PHP:

1. What is Object?

2. What is a Class?

3. PHP Class Attribute.

4. Class Method?

5. Constructor in PHP?

6.  Destructor in PHP?

7. What is Access Specifiers?

8. What is $this Variable?

9.  InstanceOf Operator in PHP?

10. How to Define Class Constants in PHP?

11. Static Data Members and Methods in PHP?

13. Defining Final Class and Final Method in PHP?

14. Exception in PHP?

15. Inheritance in PHP

16. Abstract Class and interface in PHP

17. Polymorphism in PHP

18. Overloading and Overriding in PHP

 

PHP Operator precedence

PHP Magic constants

PHP 7 Data Types

Variables can store data of different types, and different data types can do different things. PHP 7 supports 10 primitive data types that can be categorized further in 3 types:

  1. Scalar Types
  2. Compound Types
  3. Special Types

PHP Data Types: Scalar Types

There are 4 scalar data types in PHP

  1. boolean
  2. integer
  3. float (aka double)
  4. string

PHP Data Types: Compound Types

Four compound types:

 1. array

2.object

3. callable

4. iterable

PHP Data Types: Special Types

There are 2 special data types in PHP.

  1. resource
  2. NULL

Note: To check the type and value of an expression, use the var_dump() function or use the gettype() function. To check for a certain type use is_type functions. Some examples:

[php]

<?php
$my_bool = TRUE; // a boolean
$my_str = “Sani”; // a string
$my_str2 = ‘Kamal’; // a string
$my_int = 12; // an integer
$my_double=45.89; // a double
echo var_dump($my_double).”<br>”; // prints out: float(45.89)
echo var_dump($my_int).”<br>”; //prints out:int(12)
echo gettype($my_bool).”<br>”; // prints out: boolean
echo gettype($my_str).”<br>”; // prints out: string
echo gettype($my_double).”<br>”; // prints out:double
// If this is a double, increment it by 3.6
if (is_double($my_double)) {
$my_double+=3.6;
}
// If this is a string, concanate “Hi…”
if (is_string($my_str)) {
$my_str.=” Hi…”;
}
// If $my_bool is a string, print it out
// else print “Something else”
if (is_string($my_bool)) {
echo”String: $my_bool”;
}else{
echo”Something else”;
}
?>

[/php]

 

PHP Operator precedence

image056The precedence of an operator specifies how “tightly” it binds two expressions together. In general, operators have a set precedence, or order, in which they are evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example, in the expression 8 + 5 * 2, the answer is 18  and not 26 because the multiplication (“*”) operator has a higher precedence than the addition (“+”) operator. Parentheses may be used to force precedence, if necessary. For instance: (8+2) * 4 evaluates to 40.

Associativity

Operators also have an associativity.
When operators have equal precedence their associativity decides how the operators are grouped.
For example:
- is left-associative, so 5 - 8 - 4 is grouped as (5 - 8) - 4 and evaluates to -7.
= is right-associative, so $x = $y = $z is grouped as $x = ($y = $z).

The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping.

N.B:Below table taken from php official documentation. More on php.net

Associativity Operators Additional Information
non-associative clone new clone and new
left [ array()
right ** arithmetic
right ++ ~ (int) (float) (string) (array) (object) (bool) @ types and increment/decrement
non-associative instanceof types
right ! logical
left * / % arithmetic
left + . arithmetic and string
left << >> bitwise
non-associative < <= > >= comparison
non-associative == != === !== <> <=> comparison
left & bitwise and references
left ^ bitwise
left | bitwise
left && logical
left || logical
right ?? comparison
left ? : ternary
right = += -= *= **= /= .= %= &= |= ^= <<= >>= assignment
left and logical
left xor logical
left or

Example: Associativity

[php]


<?php
$a = 9 * 3 % 6; // (9 * 3) % 6 = 3
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$x = 3;
$y = 2;
$x = $y += 3; // $x = ($y += 3) -> $x = 5, $y = 5
?>

[/php]

 

PHP Magic constants

HTML5 article Element

PHP Magic constants

magic.pngPHP provides a large number of predefined constants to any script which it runs. Magic constants have a funny syntax, placing two underscores before and after the constant’s word representation. There are nine magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it’s used on in your script. These special constants are case-insensitive.
A few “magical” PHP constants ate given below:

Name Description
__LINE__ Represents current line number where it is used.
__FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__ The function name.
__CLASS__ The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ The class method name.
__NAMESPACE__ Represents the name of the current namespace.
ClassName::class The fully qualified class name.

Example of magical constants __LINE__ ,__FILE__ and __DIR__

<?php
echo "Line number " . __LINE__ ."
"; // Displays: Line number 2

echo "Line number " . __LINE__ ."
"; // Displays: Line number 3
// Displays the absolute path of this file

echo "The full path of this file is: " . __FILE__;
// Displays the directory of this file

echo "The directory of this file is: " . __DIR__;
?>

Example of magical constants __FUNCTION__, __METHOD__ , __CLASS__ and __NAMESPACE__


namespace MyNamespace;

class PrintFunMethod
{
function print_func()
{
echo __FUNCTION__;
}
function print_method()
{
echo __METHOD__;
}
function getClassName(){

return __CLASS__;

}
function getNamespace(){

return __NAMESPACE__;

}
}
$obj=new PrintFunMethod();
$obj->print_func();
output will be ---- print_func()
$obj->print_method();
output will be ----- trick::print_method
echo $obj->getClassName(); // Displays: PrintFunMethod
echo $obj->getNamespace(); // Displays: MyNamespace

PHP superglobal variables

The complete list of superglobals variables:
1. $GLOBALS—An array of all global variables (Like the global keyword, this allows
you to access global variables inside a function—for example, as
$GLOBALS[‘myvariable’].)
2. $_SERVER—An array of server environment variables
3. $_GET—An array of variables passed to the script via the GET method
4. $_POST—An array of variables passed to the script via the POST method
5. $_COOKIE—An array of cookie variables
6. $_FILES—An array of variables related to file uploads
7. $_ENV—An array of environment variables
8 $_REQUEST—An array of all user input including the contents of input including
$_GET, $_POST, and $_COOKIE (but not including $_FILES)
9. $_SESSION—An array of session variables

Understanding Variable Scope

The term scope refers to the places within a script where a particular variable is visible.
The six basic scope rules in PHP are as follows:
1. Built-in superglobal variables are visible everywhere within a script.
2. Constants, once declared, are always visible globally; that is, they can be used inside and outside functions.
3. Global variables declared in a script are visible throughout that script, but not inside
functions.
4. Variables inside functions that are declared as global refer to the global variables of
the same name.
5. Variables created inside functions and declared as static are invisible from outside
the function but keep their value between one execution of the function and the
next.
6. Variables created inside functions are local to the function and cease to exist when
the function terminates.
The arrays $_GET and $_POST and some other special variables have their own scope
rules.They are known as superglobals or autoglobals and can be seen everywhere, both
inside and outside functions.