Magic Constants and Magic Functions in PHP

In this article we will explore Magic Constants and Magic Methods, how they are useful to us? and what exactly they are?

In this article we will explore Magic Constants and Magic Methods, how they are useful to us? and what exactly they are?

So let’s understand Magic Constants first.

Magic Constants

Magic Constants are those constant whose value is going to be defined in the time of compilation. That is why they are also defined as Compile Time Constant.

There are nine magical constants that change depending on where they are used. For example, __FILE__ value depends on which file you are calling constant. It will give that filename. If you again call it in some another file its value will be changed and this time it will give the filename where you have accessed it.

This is magic of these type of Constants.

 

Name Description
__LINE__ The current line number of the file.
__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. 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.
__METHOD__ The class method name. (It will return function name along with the classname)
__NAMESPACE__ The name of the current namespace.
ClassName::class The fully qualified class name. See also ::class.

These Constants we use when we need to debug or we are creating a logging system in our application. So that we will be able to track the process is going as we thought or if something went wrong we will be able to track it.

I hope whenever you are creating your logging mechanism you will use these Magic Constants.

 

Now let’s discuss Magic Methods.

Magic Methods

There are methods which start with “__” in PHP classes which are magical in nature. If you want these magic should be associated with them so do not define methods as defined below:

 

Name Description
__construct() It gets called when an object instantiated.
__destruct() When object is not referenced by any other variable then this will be called.
__call() __call() is triggered when invoking inaccessible methods in an object context.
__callStatic() __callStatic() is triggered when invoking inaccessible methods in a static context.
__get() __get() is utilized for reading data from inaccessible properties.
__set() __set() is run when writing data to inaccessible properties.
__isset() __isset() is triggered by calling isset() or empty() on inaccessible properties.
__unset() __unset() is invoked when unset() is used on inaccessible properties.
__sleep() use of __sleep() is to commit pending data or perform similar cleanup tasks.
__wakeup() __wakeup() is to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks.
__toString() The __toString() method allows a class to decide how it will react when it is treated like a string
__invoke() The __invoke() method is called when a script tries to call an object as a function.
__set_state() This static method is called for classes exported by var_export() since PHP 5.1.0.
__clone() An object copy is created by using the clone keyword (which calls the object’s __clone() method if possible)
__debugInfo() This method is called by var_dump() when dumping an object to get the properties that should be shown.

FIREBASE: How To Send Topic Notification in IOS App

To send Topic Notification in IOS for which we need Firebase Access Key and users should have subscribed to the topic in your app which you will need to do it internally using Firebase SDK in IOS app.

Here is the sample of PHP code through which you can send IOS notification to users Topicwise.

<?php
define( 'API_ACCESS_KEY', 'KEY-VALUE' );
$msg = array
(
'body' => "abc",
'title' => "Hello from Api",
'vibrate' => 1,
'sound' => 1,
);
$body = array (
"to" => "/topics/news",
"notification" => array(
"body" => "hello there",
"sound" => "default"
),
"data" => array(
"body" => "hello there",
"title" => "IBC24",
"key_1" => "Data for key one",
"key_2" => "Data for key two"
)
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $body ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
?>

Custom week range in PHP

How to get create customized  week range in PHP

Here we have created a week range from Saturday to Friday by passing any date of the month and the day from which we need to start our week.

<?php
echo "<pre>".print_r(monthArr("05-03-2018","Saturday"),true);
function monthArr($date,$startDay){
$date = strtotime($date);
$date = "01-".date("m",$date)."-".date("Y",$date);
$firstDateOfCustomWeek = date("d-m-Y",strtotime("next ".$startDay, date(strtotime($date))));
$lastDayOfMonth = date("d-m-Y",(strtotime("+1 month", date(strtotime($date)))-1));
$arr = array();
$count = strtotime($firstDateOfCustomWeek);
while($count < strtotime($lastDayOfMonth." 23:59:59")){
$arr[] =  array(date("d-m-Y",$count),date("d-m-Y",strtotime("+6 days",date($count))));
$count =  strtotime("+7 days",date($count));
}
return $arr;
}
?>

Output

Array
(
[0] => Array
(
[0] => 03-03-2018
[1] => 09-03-2018
)
[1] => Array
(
[0] => 10-03-2018
[1] => 16-03-2018
)
[2] => Array
(
[0] => 17-03-2018
[1] => 23-03-2018
)
[3] => Array
(
[0] => 24-03-2018
[1] => 30-03-2018
)
[4] => Array
(
[0] => 31-03-2018
[1] => 06-04-2018
)
)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Install PHP OAuth in windows to enable OAuth Authentication

 

In many cases, we need to interact with APIs which having OAuth authentication to verify the request from the user. And these web services only expose data to users, once users got the authenticated token and secret key.

These authentications are used by many vendors like Twitter, Facebook to share tweets to third-party applications, there are many e-commerce applications which are using OAuth authentication to share product, orders, invoice and others details to the third-party.

How to enable classes defined in PHP to deal with OAuth Authentication?

First, let’s check if installed PHP in your system has already OAuth enabled.

So to check PHP configuration we use

echo phpinfo();

Try to find OAuth Configuration

OAuth configuration

Now if you already have this configuration enabled then you don’t need to do anything to enable OAuth configuration.

If not,

  1. go to url : http://windows.php.net/downloads/pecl/releases/oauth/1.2.3/
  2. Then download the suitable version of OAuth according to PHP version.
  3. Open the folder and find php_oauth.dll file.
  4. Now copy this file and put it in  “[WAMP_LOCATION]\bin\php\php7.0.23\ext”
  5. We have added this dll. So that PHP will be able to get the definition of OAuth class defined in PHP.
  6. Now open php,ini file

location php.ini file

 

Now open this file and below-mentioned code at the end of the file

extension=php_oauth.dll

To see the changes, restart you wamp and check using phpinfo()

Now you will be able to find OAuth configuration setting.

Or you can also try to instantiate OAuth class in PHP

$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);

 

OAuth Authentication is very useful when you really don’t want others to access the API without proper authentication.

I hope you found this article useful.

Read other interesting articles
  1. PHP TRAITS
  2. PHP ENCAPSULATION

 

Understand the concept of PHP traits with examples

 What is PHP Traits?

The concept of Traits is introduced in PHP 5.4, which is basically a group of functions which can be used in any other classes.

To overcome the problem of Multiple Inheritance, PHP introduced traits which is very much welcomed by PHP community.

It let you reuse your code in the much better way. And the combination of Traits and Classes are great when it is used in real programming because it reduces the complexity of code which arises due to the use of the Single Inheritance.

How can we create a Trait in PHP?

Syntax to create a trait in PHP:

1
2
3
4
5
trait MyFirstTrait{
public function traitMethod1(){
// code to do something
}
}

How can we use Trait Method inside a Class?

Traits Methods can be used in Class by using use keyword.

Syntax to use traits in class:

1
2
3
4
5
6
class SampleClass{
use MyFirstTrait; // use already created traits as above
public function classMethod(){
$this-&gt;traitMethod1();
}
}

Can we use more than one trait in a single Class?

Yes we can use multiple traits inside a single class

Sample code to use Multiple Traits :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
trait MyFirstTrait{
public function traitMethod1(){ 
echo "traitMethod1";
} 
}
trait MySecondTrait{
public function traitMethod2(){ 
echo "traitMethod2";
} 
}
class SampleClass{ 
use MyFirstTrait, MySecondTrait; 
public function classMethod1(){ 
$this-&gt;traitMethod1(); 
}
public function classMethod2(){ 
$this-&gt;traitMethod2(); 
} 
}

What if two traits contain methods of same name?

If two traits contain methods of same name then PHP will throw fatal error.

We can solve this condition by resolving the conflict using insteadof keyword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
trait MyFirstTrait {
public function traitMethod() {
echo 'Hello World1!';
}
}
trait MySecondTrait { 
public function traitMethod() {
echo 'Hello World2!';
}
}
 
class SampleClass{
use MyFirstTrait, MySecondTrait{
MyFirstTrait::traitMethod insteadof MySecondTrait;
}
 
public function classMethod(){
echo $this-&gt;traitMethod();
}
}
 
$sampleObj = new SampleClass();
$sampleObj-&gt;classMethod();

Can a trait use another trait?

Yes, we can use a trait inside another trait.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
trait MyFirstTrait{
public function traitMethod1(){
echo "traitMethod1";
}
}
trait MySecondTrait{
public function traitMethod2(){
echo "traitMethod2";
}
}
trait MyThirdTrait{
use MyFirstTrait, MySecondTrait;
}
class SampleClass{
use MyThirdTrait;
public function classMethod1(){
$this-&gt;traitMethod1();
}
public function classMethod2(){
$this-&gt;traitMethod2();
}
}
 
$sampleObj = new SampleClass();
$sampleObj-&gt;classMethod1();
$sampleObj-&gt;classMethod2();

Some more points to remember while using Traits

1
2
3
trait MyFirstTrait{ 
public function traitMethod1();
}
  • We can change the visibility of traits methods inside a class where we are using traits.
1
2
3
4
5
6
trait MyFirstTrait{ 
public function traitMethod1(){// do something};
}
class SampleClass{
use MyFirstTrait{ traitMethod1 as protected;}
}
  • We can also define a variable inside traits which can be used by a class.
1
2
3
trait MyFirstTrait{ 
public variable1 = "Hello World";
}

Traits are not to allowed to instantiate, It can be used with class only. But using too many traits with a class, it will increase the unnecessary responsibilities of a class which is not needed and not desirable for the coding standard.  I hope you enjoyed the articles. Please comment if you like the articles

Understand the concept of Interface in PHP

What is Interface?

An Interface contains methods without body i.e {}. Means, there we get only the declaration of the function, not the definition of the function.

A class which uses interface have to implement all of its methods declared in the interface.

Interface restricts the user to define all the method declared in the Interface in a class, which uses the interface.

How can we define an Interface?

In PHP we can define an Interface using interface keyword before the interface name as we defined below

interface MyFirstInterface{
// required code
}

Interface can have only Abstract Methods and Constant Variables

interface MyFirstInterface{
 const CONSTANT1 = 25; // contant variable
const CONSTANT2 = 50; // constant variable
public function method1();   // Abstract Method
}

How can we use Interface?

The interface can be used by the class using implements keyword.

public class MyClass implements MyFirstInterface{
   public function method1(){
// body of method1
}
}
public class MyClass implements MyFirstInterface, MySecondInterface{  
public function method1(){ 
// body of method1
} 
}
// MyFirstInterface and MySecondInterface are interface here.

This how we can use multiple interfaces at once with a Class.

The interface can be used by another interface using extends keyword.

public interface MySecondInterface implements MyFirstInterface{   
        public function method2(); // abstract method;
}

Why Should we use Interface?

When you want some user who uses your code, should implement some method according to their need which will be customizable by the user. And you want user must implement specific methods. which will be needed by your code.

In these case, you need to define Interface which will restrict the user to implement these methods.

For example:

You are creating Article Publishing Workflow. So to restrict the user to implement compulsory methods in their ArticleWorkflow Class you will need to create an interface.

interface Workflow{
public function draft();
public function sendForReview();
public function sendForPublished();
}

This workflow can be used in Article Publishing Class or Image Publishing Class or Video Publishing Class etc. So Whenever you need to create a workflow you just need to implement this interface only, then this interface will decide the what method should be implemented while creating a workflow class. So by defining the workflow interface you just created a standard process to introduce a New Workflow in the system.

I hope you found this post useful and Happy Learning.

 

 

Concept of Abstraction in PHP

We have completed the understanding of Encapsulation and Inheritance. Now let’s move on to the concept of Abstraction in PHP.

So how can we define Abstraction?

In one way hiding unnecessary details or implementation about the functionality from the user is called  Abstraction.

For Example:-

We all use the functionality of mobile phones like a phone call, send a message, play video etc. But we don’t the implementation of these features on a hardware level and software level. We just use these functionalities without taking care of others things. So here is an Abstraction between the User and the implementation of the functionality.

Why is it important to have this in our programming?

Let’s assume A developer has written a code let’s say, for sending an email. So the developer has written thousands of line of code to send an email. Now, this code is running properly and we are able to send our email. Now do we need to know the code and the meaning of each line of code for sending an email or we just need to call the functionality for sending the email. Which is good and time saver. You Decide!!

So how can we achieve the Abstraction in PHP

We can implement Abstraction in PHP by using concepts below:-
  1. Abstract Classes

Using above example of implementing the functionality of email sending. Now a developer has developed the code to implement the functionality. But for sending an email you will need some input from the user who uses that code. So to restrict that user PHP has the abstract method inside the abstract class. So the developer will write sending email process code inside an Abstract Class.

Abstract Class

A class having one or more abstract method as its member function is called an Abstract Class.

abstract class Shape2d{
public $length;
public $width;
public $sides; public function setLenth();
public function setWidth();
public function setSides();
public function calculatePerimeter(){
// code to calculate perimeter of shapes
} 
} //This is how we define an Abstract Class

 

Some points are required to remember while using Abstract Function:

1. Abstract Class cannot be instantiated.
2. Concrete Class is required to be implemented to use Abstract Class.
3. Abstract Class has to be inherited using “extends” keywords.
4. Abstract is a generalized concept of implementation of Concrete Class.

 

 

Concept of Inheritance in PHP

It is one of the important programming principle in OOPs Concepts. It will let you to code in a more modular way by which you will be able to reuse your code. It introduces the parent and child class concepts in programming language. To implement the inheritance in PHP we use “extends” keyword.

For example, we have two class

  1. Person
  2. Employee

Now let’s decide the relationship between these two classes.

Here Person Class is parent class and Employee is a child class

Person Class is parent class because it shows more primitive information as comare to Employee class.

For example

what a Person Class shows us:-

  1. Gender : male/female.
  2. Name.
  3. Address.
  4. color.
  5. height.

What a Employee Class shows us:-

  1. Gender : male/female
  2. Name
  3. Address
  4. color
  5. height
  6. employee id
  7. employee department
  8. employee salary

These two classes are just for example otherwise it will show much information.

So let’s take close look at employee class here Gender, Name, Address, Color, Height are common with person class. So why do we define it again in Employee, it’s not good programming practice. So what we will do in this case

We define an Employee Class with three attributes only as below mentioned:-

  1. employee id
  2. employee department
  3. employee salary

And others will be inherited from Person Class.

How can we implement inheritance in PHP

class Person{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
}
class Employee extends Person{
public $employee_id;
public $employee_dept;
public $employee_sal;
}
$employee = new Employee();
var_dump($employee); // try this;

Types of inheritance possible with PHP

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Hierarchical Inheritance

Single Inheritance :

Single Inheritance consists of a single parent class and will have one child class. This kind of relationship comes from single inheritance. Above mentioned relationship between Person and Employee class is also an example of Single Inheritance.

Multilevel Inheritance :

Multilevel inheritance will have a chain of single inheritance. For example, there is parent and child relationship between Person and Employee class, Now If we define a Manager class which will inherit the employee class. Then this type of inheritance will create a Multilevel Inheritance.

class Person{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
}
class Employee extends Person{
public $employee_id;
public $employee_dept;
public $employee_sal;
}
class Manager extends Employee{
public $department;
public $manager_id;
public $reporting_manager;
}
$mgr1 = new Manager();
var_dump($mgr1); // try this;

Hierarchical Inheritance :

Hierarchical inheritance consists of a single parent class and that parent class is inherited by multiple child class. For Example, there is a parent class named Person and we have two child class named Employee and Student. Both these class inherit Person class. This type of the relationship comes from hierarchical inheritance.

Try out yourself for Hierarchical Inheritance.

 

Inheritance in PHP
Inheritance in PHP

Note:

  1. Multiple Inheritance is not supported in PHP
  2. We cannot use extend keyword with Final Class.
  3. Inheritance represents the IS-A relationship. For Example “Employee is a Person”.
  4. we access parent class property inside child class using parent keyword.
  5. For Interfaces, we use implement keyword to inherit its property.

Inheritance facilitates the code reusability feature which makes it one of the most important principles of OOPs Concepts.

Concept of Encapsulation in PHP

PHP Encapsulation

Wrapping up of the data into a single unit is called Encapsulation in Object-Oriented Programming Languages. Many people get confused when someone asked them to explain it with some examples. This Concept will come in your way every time when you go for an interview.

So now let’s understand the concept of Encapsulation in OOPs in detail.

Meaning of

Wrapping up of the data into a single unit

It means defining Class Member Variables and Member function inside the class. So when we create a class and define some member variables and function inside the class it becomes a single unit which will be known by the class name together.

This small statement has a very deep meaning.

Why we need Encapsulation?

When we wrap our data into something then it hides details from the user who uses it.

For example: When we create an Object from a Class we don’t know what has been written inside the constructor. How it initializes the value of the member variable, How member function we use through object manipulates the value of the member variables or how it generates the output.

This is the main reason for which we use encapsulation so that unnecessary details should be hidden from users who use the class. To achieve this we often make Member Variables private, So that it cannot be accessed outside the class and if someone wants to access these variable, it should be through the GETTER and SETTER methods.

Example of Encapsulation:-

class Person{
private $name;
public $gender; 
public $address; 
public $height; 
public $color; 
public $race; 
public function __construct($name){ 
$this->race = "human"; 
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function setName($name){
$this->name = $name;
}
}

So due to Encapsulation, we are able to achieve Data hiding in OOPs.

So finally the concept of Encapsulation in PHP is hiding internal information of an object to protect from the other object.

This is the simple example of encapsulation with the use of Person Class. But sometimes overuse of inheritance undermines encapsulation in Object Oriented Programmings which we need to take care.

Reference from Wikipedia:

Because inheritance exposes a subclass to details of its parent’s implementation, it’s often said that “inheritance breaks encapsulation”

Gang of Four, Design Patterns
In next articles, we will discuss Inheritance and their types supported by PHP.

 

 

 

Concepts of Constructors, Destructors and its types in PHP

In this section, we will talk about constructors, destructors, their types and some important characteristics

Constructors

Let’s start with some common characteristics of Constructor

  1. We can define a constructor method by defining the __construct method inside the class.
  2. It runs only one time while creating an Object from the Class.
  3. It is the suitable place to initialize your class member variables.
  4. We should always use the __construct method instead of old-style class_name() constructor method as it is going to be deprecated in PHP 7.
  5. To call a parent class constructor in child class you can use parent::__construct().
  6. Parent class constructor is not implicitly in the child class, you need to call it as above explained in child class if the constructor is not defined private.

Syntax to define constructor in PHP

class Person{
public $name;
public $gender; 
public $address; 
public $height; 
public $color; 
public $race; 
public function __construct(){ 
$this->race = "human"; 
} 
}

Old style constructor in PHP treated as constructor in till PHP 5.3.2 now treated as normal method inside a class

class Person{
public $name;
public $gender; 
public $address; 
public $height; 
public $color; 
public $race; 
public function Person(){ 
$this->race = "human"; 
} 
}
how to call parent class constructor inside child class constructor
class Person{
public $name; 
public $gender; 
public $address; 
public $height; 
public $color; 
public $race; 
public function __constuct(){ 
$this->race = "human"; 
} 
} 
class Employee extends Person{ 
public function __constuct(){ 
parent::__construct(); // it will Person class constructor 
} 
} 
$emp1 = new Employee(); // it will call employee and parent class constructor both.

Types of constructors we have in PHP

  1. Default.
  2. Parameterized
  3. Copy Constructor

 

Default Constructors

class Person{
public $name; 
public $gender; 
public $address; 
public $height; 
public $color; 
public $race;
// if __construct() is not defined inside the class then the implicit constructor will called which is a Default Constructor 
}

Parameterized Constuctors

class Person1{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
public function __construct(){ // parameterized constructor with no-argument
$this->race = "human";
} 
}
$perObj1 = new Person1(); // parameterized constructor with no-argument
class Person2{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
public function __construct($name){ // parameterized constructor with name argument
$this->race = "human";
$this->name = $name; 
} 
}
$perObj2 = new Person2("mike"); // parameterized constructor with name argument

 

Copy Constructors

class Person1{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
public function __construct($name){ // parameterized constructor with name argument
$this->race = "human";
$this->name = $name; 
}
public function __clone(){ 
echo "do something";
} 
}
$perObj2 = new Person1("mike"); // parameterized constructor with name argument
$perObj3 = clone $perObj2; // copy constructor initialize $perObj3 with the values of $perObj2
echo "<br/>".$perObj3->name;
Output : 
do something
mike

Destructors

Characteristics of Destructor:

  1. It also gets called only once in the lifetime of an Object.
  2. It gets called at the end of execution of PHP script, function or while calling exit(); in the PHP script.
  3. It is used to free up memory space consumed by Object.
  4. Its called implicitly by the garbage collector once it knows that the particular object is of no use. So garbage collector calls it to free memory space consumed by Desctructor.
  5. To define a destructor we need to define a __destruct() method inside the class.
  6. For a Class, the __destruct method will be only one.
class Person1{
public $name;
public $gender;
public $address;
public $height;
public $color;
public $race;
public function __construct($name){ 
$this->race = "human";
$this->name = $name; 
}
function __destruct() { //syntax to define a destruct
    print "Destroying " . $this->name . "\n";
} 
}