class ClassName {
public static function staticMethod() {
echo "Hello World!";
}
}
?>
Warta Lab is one of the best websites for tutorials on PHP, Drupal, Drupal 8, and general programming topics. Visit us for expert solutions, in-depth guides, and valuable programming knowledge
<?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";} ?>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.
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>).
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.
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
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
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.
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
A number can be written in reverse order. For example 12345 = 54321 <?php $ num = 23456; $ revnum = 0; while ($ num > 1) { $...