Self vs static in php

class A {
    public static function className(){
        echo __CLASS__;
    }

    public static function test(){
        self::className();
    }
}

class B extends A{
    public static function className(){
        echo __CLASS__;
    }
}

B::test();

This will print

A

In the other hand with static:: It has the expected behaviour

class A {
    public static function className(){
        echo __CLASS__;
    }

    public static function test(){
        static::className();
    }
}

class B extends A{
    public static function className(){
        echo __CLASS__;
    }
}


B::test();

This will print

B

What are magic functions?

  • Magic Methods¬†allow you to react to certain events when using these particular objects. This means when certain things happen to your object, you can define how it should react in that instance.
  • They start with double underscore
  • They are always defined inside of the class
  • They are never called directly

 

Examples:

__construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone() and __debugInfo()

What is polymorphism?

The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way.

A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task.

In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.

 

Source here.

What demonstrates good code quality?

Efficient, reliable, high availability (services), secure, maintainable, reusable, extensible.

Good code is easy to understand, use, and maintain. Variables, functions, classes, etc, should be named in an appropriate manner, enabling the next person after you to effectively reuse or modify them.

It should be well tested. The code should have high test coverage – this will help you write code that works thoroughly, and help avoid any regressions in code functionality once more work is done on it in the future.

The code should demonstrate low coupling and high cohesion. From stackoverflow:

Cohesion refers to what the class (or module) will do. Low cohesion would mean that the class does a great variety of actions and is not focused on what it should do. High cohesion would then mean that the class is focused on what it should be doing, i.e. only methods relating to the intention of the class.

Example of Low Cohesion:

-------------------
| Staff           |
-------------------
| checkEmail()    |
| sendEmail()     |
| emailValidate() |
| PrintLetter()   |
-------------------

Example of High Cohesion:

----------------------------
| Staff                   |
----------------------------
| -salary                 |
| -emailAddr              |
----------------------------
| setSalary(newSalary)    |
| getSalary()             |
| setEmailAddr(newEmail)  |
| getEmailAddr()          |
----------------------------

As for coupling, it refers to how related are two classes / modules and how dependent they are on each other. Being low coupling would mean that changing something major in one class should not affect the other. High coupling would make your code difficult to make changes as well as to maintain it, as classes are coupled closely together, making a change could mean an entire system revamp.

All good software design will go for high cohesion and low coupling.

 

Source here.

Tower of Hanoi in PHP

<?php


function moveTower($height, $fromTower, $toTower, $viaTower)
{
	echo $height  . "<br>";
	if ($height >= 1)
	{	
		moveTower($height-1, $fromTower, $viaTower, $toTower);
		moveDisk($fromTower, $toTower);
		moveTower($height-1, $viaTower, $toTower,  $fromTower);
	}
	else
	{
		//moveDisk($fromTower, $toTower);
	}
	
}

function moveDisk($a, $b)
{
	echo "Moving disk from" . $a . " to " . $b . "<br>";
}


moveTower(3, 'A','B','C');
exit; 

PHP Implementation of Singly Linked List

<?php

class listNode {

    function __construct($data) {
        $this->data = $data;
        $this->next = null;
    }

}

class linkedList {

    function __construct() {

        $this->head = NULL;
    }

    function insert($data) {
        $node = new listNode($data);
        $node->next = $this->head;
        $this->head = $node;
        //if ()
    }

}

class reverse {

    function reversing($obj) {

        $current = $obj->head;
        print_r($current);
        $previous = null;
        $a = 0;
        while ($current != null) {
            echo $a++;
            $head = $current->next;
            $current->next = $previous;
            $previous = $current;
            $current = $head;
        }
        $obj1 = $previous;
        print_r($obj1);
    }

}

$myLinkedList = new linkedList();
$myLinkedList->insert(1);
$myLinkedList->insert(2);
$myLinkedList->insert(3);
$myLinkedList->insert(4);
$myLinkedList->insert(5);
$myLinkedList->insert(6);
//$myLinkedList->insertBegin(4);
echo "Reverse<br>";
$myReverse = new reverse();
$myReverse->reversing($myLinkedList);




What is a singleton pattern?

Singleton pattern solves the problem of having a one and only one instance of a class in your project. Singleton is nothing more than a fancy name for a global variable.

 

<?php
class Singleton
{
    /**
     * @var Singleton The reference to *Singleton* instance of this class
     */
    private static $instance;
    
    /**
     * Returns the *Singleton* instance of this class.
     *
     * @return Singleton The *Singleton* instance.
     */
    public static function getInstance()
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }
        
        return static::$instance;
    }

    /**
     * Protected constructor to prevent creating a new instance of the
     * *Singleton* via the `new` operator from outside of this class.
     */
    protected function __construct()
    {
    }

    /**
     * Private clone method to prevent cloning of the instance of the
     * *Singleton* instance.
     *
     * @return void
     */
    private function __clone()
    {
    }

    /**
     * Private unserialize method to prevent unserializing of the *Singleton*
     * instance.
     *
     * @return void
     */
    private function __wakeup()
    {
    }
}

class SingletonChild extends Singleton
{
}

$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance());             // bool(true)

$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance());      // bool(false)

var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)