Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

Static Keywords - Understanding of Static Functions , Method and Static Variables in PHP

Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. These can also be accessed statically within an instantiated class object.

Any method declared as static is accessible without the creation of an object. Static functions are associated with the class, not an instance of the class. They are permitted to access only static methods and static variables. To add a static method to the class, static keyword is used.

Static methods are call without  creating an instance of the object,  so the pseudo-variable $this is not available inside methods declared as static.

Static methods are declared with the static keyword:

Syntax - 

<?php
class ClassName {
  public static function staticMethod() {
    echo "Hello World!";
  }
}
?>


To access a static method use the class name, double colon (::), and the method name:

ClassName::staticMethod();

Example: This example illustrates static function as counter.

<?php
/* Use static function as a counter */
  
class solution {
      
    static $count;
      
    public static function getCount() {
        return self::$count++;
    }
}
  
solution::$count = 1;

for($i = 0; $i < 5; ++$i) {
    echo 'The next value is: '. 
    solution::getCount() . "\n";
}
  
?>

Output:
The next value is: 1
The next value is: 2
The next value is: 3
The next value is: 4
The next value is: 5

Static properties
Static properties are accessed using the Scope Resolution Operator (::) and cannot be accessed through the object operator (->).

PHP Sessions

Session handling is a key concept in PHP that enables user information to be persisted across all the pages of a website or app. In  other words . An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path.

When a session is started following things happen .

PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.

A cookie called PHPSESSID is automatically sent to the user's computer to store unique session identification string.

A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_  ie sess_3c7foj34c3jj973hjkop2fc937e3443.

When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.

A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session

 The first step is to start up a session. After a session is started, session variables can be created to store information. The PHP session_start() function is used to begin a new session.It als creates a new session ID for the user. Below is the PHP code to start a new session.

<?php

session_start();

?>

Storing Session Data

Session data in key-value pairs using the $_SESSION[] superglobal array.The stored data can be accessed during lifetime of a session.

Below is the PHP code to store a session with two session variables Rollnumber and Name.

<?php

session_start();

$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";

?>

Accessing Session Data

Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing the corresponding key to the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber and Name is shown below.

<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';
echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';

?>

Output - 

The Name of the student is :Ajay 
The Roll number of the student is :11

Destroying Certain Session Data

To delete only a certain session data,the unset feature can be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session array.

<?php

session_start();

if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}

?>

Destroying Complete Session

The session_destroy() function is used to completely destroy a session. The session_destroy() function does not require any argument.

<?php

session_start();
session_destroy();

?>

Key Points

The session IDs are randomly generated by the PHP engine .
The session data is stored on the server therefore it doesn’t have to be sent with every browser request.
The session_start() function needs to be called at the beginning of the page, before any output is generated by the script in the browser.


PHP Cookies

 Cookie is a small piece of information stored as a file in the user's browser by the web server. Once created, cookie is sent to the web server as header information with every HTTP request.

You can use cookie to save any data but it should not exceed 1K(1024 bytes) in size.

The web works based on the HTTP protocol. The HTTP protocol is stateless.

When the web browser requests a page from a web server, the web server responds with the page content. Later, the same web browser requests the same page again, the web server has no information that the request is from the same web browser.

Cookies solve this stateless challenge.

A cookie is a piece of data that a web server sends to the web browser. The web browser may store it and send it back in the subsequent requests to the same web server. By using the same cookie, the web server knows that two requests come from the same web browser.

Cookies are also known as web cookies, HTTP cookies, or browser cookies. We’ll use the cookies to make it short.

How Cookie works

First, the web browser sends a request to the web server. The web server doesn’t have any information about the web browser. The web server creates a cookie with a name return and a value 1 and attaches the cookie to the HTTP response header. To create a cookie, you’ll use the setcookie() function.

Second, the web browser stores the cookie.

Third, the web browser sends the second request with the stored cookie in the header of the HTTP request to the web server. On the web server, PHP can access the cookie via the $_COOKIE superglobal variable and do something accordingly.

Finally, the web server responds with the content of the request. Typically, it responds to the web browser with the content based on the value of the cookie.

A web browser can store a cookie with a maximum size of 4KB. However, it’s different between web browsers.

A cookie has an expiration date. Typically, web browsers store cookies for a specific duration. And the web server can specify the expired time for a cookie.

A cookie also stores the web address (URL) that indicates where it comes from. And the web browser only sends back the cookie that was originally set by the same web address. In other words, a website won’t be able to read a cookie set by other websites.

Most modern web browsers allow users to choose to accept cookies. Therefore, you should not completely rely on cookies for storing critical data.

Types of Cookies

There are two types of cookies, they are:

Session Cookie: This type of cookies are temporary and are expire as soon as the session ends or the browser is closed.

Persistent Cookie: To make a cookie persistent we must provide it with an expiration time. Then the cookie will only expire after the given expiration time, until then it will be a valid cookie.

Creating a Cookie in PHP

In PHP we can create/set a cookie using the setcookie() function.

Below we have the syntax for the function,

setcookie(name, value, expire, path, domain, secure)

The first argument which defines the name of the cookie is mandatory, rest all are optional arguments. Let's understand what are the available arguments that we can supply to the setcookie() function to set a cookie.

name - Used to specify the name of the cookie. It is a mandatory argument. Name of the cookie must be a string.

value - Used to store any value in the cookie. It is generally saved as a pair with name. For example, name is userid and value is 7007, the userid for any user.

expire - Used to set the expiration time for a cookie. if you do not provide any value, the cookie will be treated as a session cookie and will expire when the browser is closed.

path - Used to set a web URL in the cookie. If set, the cookie will be accessible only from that URL. To make a cookie accessible through a domain, set '/' as cookie path.

domain - The domain of your web application. It can be used to limit access of cookie for sub-domains. For example, if you set the domain value as wwww.blogger.com, then the cookie will be inaccessible from wartalab.blogspot.com.

secure - If you set this to 1, then the cookie will be available and sent only over HTTPS connection.

So if we want to create a cookie to store the name of the user who visited your website, and set an expiration time of a week, then we can do it like this,

<?php

setcookie("username", "xyz", time()+60*60*24*7);

?>

To access a stored cookie we use the $_COOKIE global variable, and can use the isset() methos to check whether the cookie is set or not.

Let's have a complete example where we will set a cookie and then retrieve it to show its value in the HTML page.

<?php

// set the cookie

setcookie("username", "iamabhishek", time()+60*60*24*7);

?>

<html>

    <body>

    <?php

    // check if the cookie exists

    if(isset($_COOKIE["username"])) {

        echo "Cookie set with value: ".$_COOKIE["username"];

    } else {

        echo "cookie not set!";

    }

    ?>

    </body>

</html>

So by providing the name of the cookie inside the square brakets with the global variable $_COOKIE[] we can access the cookie.

NOTE: setcookie() function should be placed before the starting HTML tag(<html>).

PHP Interface

 An interface allows you to specify a contract that a class must implement. To define an interface, you use the interface keyword as follows.

Interfaces allow you to specify what methods a class should implement.

Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".

Syntax for defining PHP Interface

Like classes are defined using the keyword class, interfaces are defined using the keyword interface followed by the interface name.

<?php

    // interface declaration

    interface NameOfInterface {  

    }

?>

And a class uses the implements keyword to inherit from an interface and implement the methods declared in the interface.

<?php

    // class declaration

    class SomeClass implements NameOfInterface {

    }

?>

An interface consists of methods that contain no implementation. In other words, all methods of the interface are abstract methods. An interface can also include constants. For example-

<?php

interface MyInterface {

const CONSTANT_NAME = 1;

public function methodName();

}

?>

When you define a class (child class) that reuses properties and methods of another class (parent class), the child class extends the parent class.

However, for interfaces, we say that a class implements an interface. 

A class can inherit from one class only. However, it can implement multiple interfaces.

To define a class that implements an interface, you use the implements keyword as follows:

<?php

interface MyInterface {

const CONSTANT_NAME = 1;

public function methodName();

}

class MyClass implements MyInterface {

public function methodName() {

// ...

}

}

?>

When a class implements an interface, it’s called a concrete class. The concrete class needs to implement all the methods of the interface.

Like a class, an interface can extend another interface using the extends keyword. The following example shows how the Document interface extends the Readable interface.

interface Readable {

public function read();

}

interface Document extends Readable {

public function getContents();

}

Following are the reasons for using interfaces:

By implementing an interface, the object’s caller needs to care only about the object’s interface, not implementations of the object’s methods. Therefore you can change the implementations without affecting the caller of the interface.

An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.

An interface enables you to model multiple inheritances because a class can implement more than one interface.



PHP Abstract Class and Methods

Abstract classes are the classes in which at least one method is abstract. Unlike C++ abstract classes in PHP are declared with the help of abstract keyword. Use of abstract classes are that all base classes implementing this class should give implementation of abstract methods declared in parent class. An abstract class can contain abstract as well as non abstract methods.

Following are some important points about abstract class and method.

1 - An abstract class can have methods and properties just like any other normal class.

2 - An abstract class cannot be instantiated, hence we need to create a child class which extends it, then we can create object of the child class.

3 - If a class has even a single abstract method then the class should also be abstract.

4 - An abstract method is just the declaration, where we provide name of the method and argument, while the body part is empty.

Don't worry if its too much for you to understand. We will cover all the points step by step with examples, lets start by understanding how we create an abstract class.

Creating an abstract Class

To declare a class abstract, we need to use the abstract keyword before the name of the class.

 Example - 

<?php

    // abstract class

    abstract class Vehicle {

        // abstract function mileage

        abstract public function mileage() {

        }

    } 

?>

In the example above, our class Vehicle is an abstract class, which has an abstract method.

The idea behind creating abstract class is to bound developers to follow a set of guidelines, for example, if you want to create a new class which extends our class Vehicle then you will have to provide definition for the abstract method mileage(), else the child class should also be abstract. Hence, it is mandatory for all the child classes to provide definition for the method mileage().

Non Abstract Method in Abstract Class

Any class with even a single abstract method must be declared abstract. But an abstract class can have non-abstract methods as well, which can be accessed and used directly by the child classes, without overriding them.

Let's extend the example above, and include a non-abstract method in our class Vehicle.

<?php

    // abstract class

    abstract class Vehicle {

        // protected variable

        protected $name;

        // non-abstract public function start

        public function start() {

            echo $this->name. " - Engine start...<br/>";

        }

        // non-abstract public function stop

        public function stop() {

            echo $this->name. " - Engine stop...<br/>";

        }

        // non-abstract public function setName

        public function setName($name) {

            $this->name = $name;

        }

        // abstract function mileage

        abstract public function mileage() {

        }

    }

?>

In the code above, we have added three non-abstract methods namely start(), stop() and setName() to our abstract Vehicle class.

Inheriting Abstract Classes

Just like any other class, we can create classes extending abstract classes too.

The only difference here is that the child class must provide definition for the abstract method declared in the abstract parent class.

If the child class doesn't provide definition for the abstract method, then it should also be defined as an abstract class.

Let's create two child classes inheriting the class Vehicle and which will have definition for the abstract method mileage():

<?php

    // child class

    class Car extends Vehicle {

        public function mileage() {

            echo "I am " . $this->name . "<br/>";

            echo "My mileage range is - 15 to 22 Km/L";

        }

    }

?>

We can have as many child classes as we want, lets have another class.

<?php

    // child class

    class Motorcycle extends Vehicle {

        public function mileage() {

            echo "I am " . $this->name . "<br/>";

            echo "My mileage range is - 35 to 47 Km/L";

        }

    }

?>

As mentioned above that an abstract class cannot have any object, once we have proper child classes defined, we can create object for them.

<?php

    $car = new Car();

    $car->setName("BMW X1");

    $car->mileage();

?>

Output - 

I am BMW X1

My mileage range is - 15 to 22 Km/L






What is Constructor and Destructor

 Constructor is a special type of function which will be called automatically whenever there is any object created from a class.

Destructor is a special type of function which will be called automatically whenever any object is deleted or goes out of scope.

Syntax: 

__construct(): 


function __construct() {

       // initialize the object and its properties by assigning 

       //values

       }


__destruct(): 

function __destruct()  {

       // destroying the object or clean up resources here 

       }

Note: The constructor is defined in the public section of the Class. Even the values to properties of the class are set by Constructors.

Constructor types

Default Constructor:It has no parameters, but the values to the default constructor can be passed dynamically.

Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members.

Copy Constructor: It accepts the address of the other objects as a parameter.

Example

<?PHP

class Tree

{

function Tree()

{

echo "Its a User-defined Constructor of the class Tree";

}


function __construct()

{

echo "Its a Pre-defined Constructor of the class Tree";

}

}


$obj= new Tree();

?>

Output: 

Its a Pre-defined Constructor of the class Tree

Parameterized Constructor: The constructor of the class accepts arguments or parameters. 

The -> operator is used to set value for the variables. In the constructor method, you can assign values to the variables during object creation.

Example -

<?php


class Employee {

Public $name;

Public $position;

function __construct($name,$position) {

// This is initializing the class properties

$this->name=$name;

$this->profile=$position;

}

function show_details() {

echo $this->name." : ";

echo "Your position is ".$this->profile."\n";

}

}

$employee_obj= new Employee("Rakesh","developer");

$employee_obj->show_details();

$employee2= new Employee("Vikas","Manager");

$employee2->show_details();

?>

Output -

Rakesh : Your position is developer

Vikas : Your position is Manager


Constructors start with two underscores and generally look like normal PHP functions. Sometimes these constructors are called as magic functions starting with two underscores and with some extra functionality than normal methods. After creating an object of some class that includes constructor, the content of constructor will be automatically executed.

Note: If the PHP Class has a constructor, then at the time of object creation, the constructor of the class is called. The constructors have no Return Type, so they do not return anything not even void.

Advantages of using Constructors

Constructors provides the ability to pass parameters which are helpful in automatic initialization of the member variables during creation time .
The Constructors can have as many parameters as required and they can be defined with the default arguments.
They encourage re-usability avoiding re-initializing whenever instance of the class is created .
You can start session in constructor method so that you don’t have to start in all the functions everytime.
They can call class member methods and functions.
They can call other Constructors even from Parent class.

Destructor: Destructor is also a special member function which is exactly the reverse of constructor method and is called when an instance of the class is deleted from the memory. Destructors (__destruct ( void): void) are methods which are called when there is no reference to any object of the class or goes out of scope or about to release explicitly. 
They don’t have any types or return value. It is just called before de-allocating memory for an object or during the finish of execution of PHP scripts or as soon as the execution control leaves the block. 
Global objects are destroyed when the full script or code terminates. Cleaning up of resources before memory release or closing of files takes place in the destructor method, whenever they are no longer needed in the code. The automatic destruction of class objects is handled by PHP Garbage Collector.

Note: The destructor method is called when the PHP code is executed completely by its last line by using PHP exit() or die() functions.

Example - 

<?php

class SomeClass {
 
function __construct()
{
echo "In constructor, ";
$this->name = "Class object! ";
}

function __destruct() {
echo "destroying " . $this->name . "\n";
}
}
$obj = new Someclass();

?>

Output -

In constructor, destroying Class object! 

Note: In the case of inheritance, and if both the child and parent Class have destructors then, the destructor of the derived class is called first, and then the destructor of the parent class. 

Advantages of destructors
 
Destructors give chance to objects to free up memory allocation , so that enough space is available for new objects or free up resources for other tasks.
It effectively makes programs run more efficiently and are very useful as they carry out clean up tasks.
 

What is the relation between Classes and Objects

 They look very much same but are not same.

    A class is a definition, while an object is an instance of the class.

    A class is a blueprint while objects are actual objects existing in the real world.

Suppose we have a class Person which has attributes and methods like name, age, height, weight, color etc.

Class Person is just a prototype, now we can create real-time objects of class Person.


#Example: Ali is real time object of class Person, which have name=Ali, age=23, height=170cm, weight=60kg and color=black etc.

Class

A way to bind data and associated functions together.

Class have many objects.

Class is a template for creating objects.

It is logical existence.

Memory space is not allocated, when it is created.

Definition (Declaration) is created once.

Class is declared using "class" keyword.

Object

Basic runtime entity in object oriented environment.

Object belongs to only class.

Object are a implementation of class.

It is physical existence.

Memory space is allocated when it is created.

It is created many times as you required.

Object is the instance or variable of class.

PHP Method Overloading

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. 

PHP Method Overloading 

It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic methods dedicated to the appropriate purpose. Unlike property overloading, PHP method overloading allows function call on both object and static context.

 The related magic functions are.

__call(string $name, array $arguments) –  is triggered when invoking inaccessible methods in an object context.

__callStatic(string $name, array $arguments) – is triggered when invoking inaccessible methods in a static context.

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.


<?php
class Wali
{
    public function 
__call($name, $arguments)
    {
        
// Note: value of $name is case sensitive.
        
echo "Calling object method '$name' "
             
. implode(', ', $arguments). "\n";
    }

    public static function 
__callStatic($name, $arguments)
    {
        
// Note: value of $name is case sensitive.
        
echo "Calling static method '$name' "
             
. implode(', ', $arguments). "\n";
    }
}

$obj = new Wali;
$obj->runTest('in object context');

Wali::runTest('in static context');
?>


Output:

Calling object method 'runTest' in object context

Calling static method 'runTest' in static context


Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...