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.

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme

 Define all of your CSS and Javascript file or libraries in a *.libraries.yml file in your theme folder. If your theme is named custom, the file name should be custom.libraries.yml. Each "library" in the file is an entry detailing CSS and JS files (assets), like this.

# custom.libraries.yml

cuddly-slider:

  version: 1.x

  css:

    theme:

      css/cuddly-slider.css: {}

  js:

    js/cuddly-slider.js: {}

In this example, the JavaScript: cuddly-slider.js and CSS cuddly-slider.css are located in the respective js and css directories of your theme.

#Including jQuery in your Library

Remember, Drupal no longer loads jQuery on all pages by default, so for example if cuddly-slider needs jQuery you must declare a dependency on the core library that contains jQuery (Drupal core provides jQuery, not a module or theme). Declare the dependency with an extension name followed by a slash, followed by the library name, in this case core/jquery. If another library required cuddly-slider it would declare:custom/cuddly-slider, the theme name, followed by the library name. You cannot declare an individual file as a dependency, only a library.

So, to make jQuery available for cuddly-slider, we update the above to.

# custom.libraries.yml

cuddly-slider:

  version: 1.x


  css:

    theme:

      css/cuddly-slider.css: {}


  js:

    js/cuddly-slider.js: {}

  dependencies:

    - core/jquery


#Declaring dependencies

To declare a dependency, the required library is declared in the form resource/library. For core libraries, the resource is core, while for others it is the module name or the theme name. So if new_library is dependent on jQuery from core, my_library declared in my_theme, and my_library declared in my_module, you would declare the dependencies as.

# custom.libraries.yml

new_library:

  js:

    js/new_library.js: {}

  dependencies:

    - core/jquery

    - my_module/my_library

    - my_theme/my_library

The module and theme names provide namespacing for libraries of the same name.

#Attaching a library to all pages

Most themes will use a global-styling asset library, for the stylesheets (CSS files) that need to be loaded on every page where the theme is active. It is also possible to do with JS via a global-scripts asset library

# custom.libraries.yml (multiple libraries can be added to a libraries.yml file, these would appear below the cuddly-slider libraries added earlier)

global-styling:

  version: 1.x

  css:

    theme:

      css/layout.css: {}

      css/style.css: {}

      css/colors.css: {}

global-scripts:

  version: 1.x

  js: 

    js/navmenu.js: {}   

To be available everywhere in the theme, the global-styling/global-scripts libraries must then be added to your theme's info.yml (in this case custom.info.yml)

#custom.info.yml

name: Custom

type: theme

description: 'Custom theme'

core: 8.x

# by adding global-styling and global-scripts here, the css/js files in the library become 

# available to every page presented by the theme

libraries:

  - custom/global-styling

  - custom/global-scripts

base theme: classy

regions:

  header: Header

  content: Content

  sidebar_first: 'Sidebar first'

  footer: Footer


#Attaching a library via a Twig template

You can attach an asset library to a Twig template using the attach_library() function in any *.html.twig, file like so:


{{ attach_library('custom/cuddly-slider') }}

<div>Some fluffy markup {{ message }}</div>

#Attaching a library to a subset of pages

function custom_preprocess_page(&$variables) {

  $variables['page']['#cache']['contexts'][] = 'route';

  $route = "entity.node.preview";

  if (\Drupal::routeMatch()->getRouteName() === $route) {

    $variables['#attached']['library'][] = 'custom/node-preview';

  }

}




Drupal Theming - Use of template.php

 The template.php file contains your sub-theme's functions to manipulate Drupal's default markup. It is one of the most useful files when creating or modifying Drupal themes. 

template.php

A- It contains code that is run every time the template engine is run.

B- template.php is a collection of functions that assist in the theming of the site. It’s for all the conditional logic and data processing of the output - the place to redefine or override theme functions, or add variables that will be made available to the theme engine.

C- PHP: This file must start with a PHP opening tag and typically does not end with a PHP closing tag.

D- There will be one template.php file for a theme, and this one file will define any needed variables.

E- You can add new variables and template suggestions.

With template.php you ca do the following things.

1 - Modify any theme hooks variables or add your own variables, using preprocess or process functions.

2 - Override any theme function. That is, replace a module's default theme function with one you write.

3 - Call hook_*_alter() functions which allow you to alter various parts of Drupal's internals, including the render elements in forms. The most useful of which include hook_form_alter(), hook_form_FORM_ID_alter(), and hook_page_alter(). See api.drupal.org for more information about _alter functions.

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)   {   $...