PHP as OOP

We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects.

PHP: Hypertext Preprocessor (or simply PHP) is a server-side scripting language. It was originally created by Rasmus Lerdorf in 1994; PHP originally stood for Personal Home Page, but it now stands for the recursive initialism PHP: Hypertext Preprocessor. PHP 7.3 is the latest version.

Rasmus Lerdorf is a Danish-Canadian programmer.

Object Oriented Concepts

Before we go in detail, lets define important terms related to Object Oriented Programming.
  • Class − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object. A class is a template for an object, and an object is an instance of a class. Because an object is an instance of a class, you will often see the two words object and instance used interchangeably.
  • Object − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance. Instance mesans 'Can holds it's state'.
  • Member Variable − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created. The data, or variables, defined within a class are called instance variable because each instance of the class (that is, each object of the class) contains its own copy of these variables.
  • Member function − These are the function defined inside a class and are used to access object data.
  • Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.
  • Parent class − A class that is inherited from by another class. This is also called a base class or super class.
  • Child Class − A class that inherits from another class. This is also called a subclass or derived class.
  • Polymorphism(বহুরুপতা) − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it make take different number of arguments and can do different task.
  • Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation. [PHP supports overloading in a different way]
  • Overriding – Same method name with same number of property. Used in inheritance.
  • Data Abstraction(গোপন করন) − Any representation of data in which the implementation details are hidden (abstracted).
  • Encapsulation(মোড়ানো) − Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
  • Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class.
  • Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope.
  • Namespace – Used to remove naming conflicts and to classify files in a project. Details.
  • Class name are noun and method or function names are verb. Interface names are generally prefixed with I.
  • In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not case-sensitive. However; all variable names are case-sensitive!

Constructor Functions

Constructor Functions are special type of functions which are called automatically whenever an object is created. Definition in two ways:
1. PHP provides a special function called __construct() to define a constructor.
2. A constructor can be defined with the same name as the name of a class.
Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation.
function __construct( $par1, $par2 ) {
   $this->title = $par1;
   $this->price = $par2;
}
Now we don’t need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below −
$physics = new Books( "Physics for High School", 10 );
$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
This will produce the following result −
Physics for High School
  Advanced Chemistry
  Algebra
  10
  15
  7

Destructor

When object is created, it takes many resources from environment. Like a constructor function you can define a destructor function using function __destruct(). You can release all the resources with-in a destructor. This method is invoked just before the destruction of the object. A object is destroyed when there is no reference remaining of that object.

Inheritance

PHP class definitions can optionally inherit from a parent class definition by using the extends clause. The syntax is as follows −
class Child extends Parent {
   <definition body>
}
The effect of inheritance is that the child class (or subclass or derived class) has the following characteristics −
  • Automatically has all the member variable declarations of the parent class.
  • Automatically has all the same member functions as the parent, which (by default) will work the same way as those functions do in the parent.

Function Overriding

Function overriding is used in inheritance. Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

Overloading

PHP supports overloading (method and properties) in a different way than other usual object oriented programming. Overloading in PHP provides means to dynamically create properties and methods. This is done using magic methods like(__call(), __set(), __get())

Magic methods

Few reserved functions whose names starts with __ (double underscore). Two categories of magic methods:
1. Method overloading
public __call ( string $name , array $arguments ) :mixed
public static __callStatic ( string $name , array $arguments ) :mixed
Example:
<?php
class MethodTest
{
    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 MethodTest;
$obj->runTest('in object context');
MethodTest::runTest('in static context');
?>
The above example will output:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context 
2. Property overloading
public __set ( string $name , mixed $value ) : void
public __get ( string $name ) : mixed
public __isset ( string $name ) : bool
public __unset ( string $name ) : void 

Public Members

Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −
  • From outside the class in which it is declared
  • From within the class in which it is declared
  • From within another class that implements the class in which it is declared

Private members

The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class.
A class member can be made private by using private keyword infront of the member.
class MyClass {
   private $car = "skoda";
   $driver = "SRK";
   
   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   private function myPrivateFunction() {
      return("I'm  not visible outside!");
   }
}
When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private.

Protected members

A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes.
Here is different version of MyClass −
class MyClass {
   protected $car = "skoda";
   $driver = "SRK";

   function __construct($par) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
   
   function myPublicFunction() {
      return("I'm visible!");
   }
   
   protected function myPrivateFunction() {
      return("I'm  visible in child class!");
   }
}

Inheritance

PHP does support Multi-level inheritance.  It does not support multiple inheritance.

Trait


A Trait is a resource similar to a class. A trait starts with trait keywork instead of class. It encapsulates few methods which will be used in another method. Trait is used because PHP does not support multiple inheritance. Example:
trait message1 {
public function msg1() {
    echo "OOP is fun! ";
  }
}

class Welcome {
  use message1;
}

$obj = new Welcome();
$obj->msg1();

Details link

Interfaces

Interfaces are defined to provide a common function names to the implementers. Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class. You can say, interfaces are skeletons which are implemented by developers.
As of PHP5, it is possible to define an interface, like this −
interface Mail {
   public function sendMail();
}
Then, if another class implemented that interface, like this −
class Report implements Mail {
   // sendMail() Definition goes here
}

Constants

A constant is somewhat like a variable, in that it holds a value, but is really more like a function because a constant is immutable(অপরিবর্তনীয়). Once you declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of MyClass −
class MyClass {
   const requiredMargin = 1.7;
   
   function __construct($incomingValue) {
      // Statements here run every time
      // an instance of the class
      // is created.
   }
}
In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant’s name does not have a leading $, as variable names do.

Abstract Classes

An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract, like this −
When inheriting from an abstract class, all methods marked abstract in the parent’s class declaration must be defined by the child; additionally, these methods must be defined with the same visibility.
abstract class MyAbstractClass {
   abstract function myAbstractFunction() {
   }
}
Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class.
If the class is an abstract but no abstract members then it will have no use.

Use of abstract and interface

When there are some common features to be shared by all the objects, then we go for abstract class.
When all the features are to be implemented differently for all the objects then we go for interfaces. Details.
Youtube link
Practical uses:
  1. One typical example is a plugin architecture. Developer A writes the main app, and wants to make certain that all plugins written by developer B, C and D conform to what his app expects of them.
  2. If I’m writing a library of code, then any random person can come along, create a class that implements that interface, instantiate an object of that class and pass it to my library code and expect it to work. Note: it is of course possible to strictly implement an interface while ignoring the intention of the interface, so merely implementing an interface is no guarantee that things will work. Stupid always finds a way! 🙂

PHP - Interfaces vs. Abstract Classes

Interface are similar to abstract classes. The difference between interfaces and abstract classes are:

  • Interfaces cannot have properties, while abstract classes can
  • All interface methods must be public, while abstract class methods is public or protected
  • All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary
  • Classes can implement an interface while inheriting from another class at the same time
  • Abstract class can have not abstract method but and Interface's all classes are abstract by default.

Static Keyword

Declaring class members or methods as static makes them accessible without needing an instantiation of the class (but in instance can be accessed using ::). Unlike instance property, a static property can't hold it's state.

Consider a class has a static variable. When multiple objects are created from this class, the static property of these objects will contain a single value. If we change the value of static property inside any object then static property of all other object will be changed.
Try out following example −
<?php
   class Foo {
      public static $my_static = 'foo';
      
      public function staticValue() {
         return self::$my_static;
      }
   }
 
   print Foo::$my_static . "\n";
   $foo = new Foo();
   
   print $foo->staticValue() . "\n";
?>

Final Keyword

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()
<?php

   class BaseClass {
      public function test() {
         echo "BaseClass::test() called<br>";
      }
      
      final public function moreTesting() {
         echo "BaseClass::moreTesting() called<br>";
      }
   }
   
   class ChildClass extends BaseClass {
      public function moreTesting() {
         echo "ChildClass::moreTesting() called<br>";
      }
   }
?>

Namespace

Suppose we have two classes or functions with the same name ie. output in different directory. When we call output() function how php will know which functiion to call. (Think link, php imports all the codes required in a single file. So the same file will contain two output() functions or two output class)

:: vs ->

This means that -> is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while :: is usually used to access static members (though in a few special cases, it’s used to access instance members).

Scope Resolution Operator (::)

The Scope Resolution Operator or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

$this vs self vs static vs parent

  1. $this vs self: Use $this to refer to the current object. Use self to refer to the current class. In other words, use $this->member for non-static members, use self::$member for static members.
  2. self:: vs static:: : If the self keyword is defined in parent class and called through the child class, will refer to the parent class. Where the static class will refer to the current (child) class. This is called Late Static Bindings.
  3. parent:: refers to the parent class name.

::class

Some times you need the class including its full namespace. This is called its “FQN”, or “fully-qualified name”. To get the fully-qualified name as string, we use ::class keyword. Example:
use \App\Console\Commands\Inspire;

//...

protected $commands = [
    Inspire::class, // Equivalent to "App\Console\Commands\Inspire"
];

Singleton pattern

A singleton class is a particular kind of class that can be instantiated only once. If try to create more than one instance, the singleton class will return only the first instance. It can be useful for database connection.
e.g.
<?php
    class DBConn {

        private static $obj;

        private final function  __construct() {
            echo __CLASS__ . " initializes only once\n";
        }

        public static function getConn() {
            if(!isset(self::$obj)) {
                self::$obj = new DBConn();
            }
            return self::$obj;
        }
    }

    $obj1 = DBConn::getConn();
    $obj2 = DBConn::getConn();

    var_dump($obj1 == $obj2);
?>
Output:
DBConn initializes only once
bool(true)
Object1 and Object2 will point to the same instance
            _______________________
           |                       |
$obj1 ---->|  Instance of DBConn   |<----- $obj2
           |_______________________| 
Singleton isn't a PHP related concept but an OOP concept.

use keyword

use keyword in php is used for aliasing and importing (not including).

Aliasing

<?php
use My\Full\Classname as Another;
//the above line provides an alias Another of the class Classname.
?>

Importing

<?php
use My\Full\Classname;
//the above line imports the Classname class but it can't be instantiated yet. Just it's full namespace will be available here.
?>
Importing does not mean including the file. In this case, the Fully Qualified Name(FQN) of the class is defined. This is useful for autoloading.

Autoloading

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that will be put into a stack/queue and call sequentially when a "new Class" is declared. 
spl_autoload_register() this function will have a function argument. This function argument will have an FQN argument of the class which was instantiated.
<?php
use Folder\Test as X;
//Here, myAutoloader is the name of the following function.
//you can also use a closure instead of the function name.
spl_autoload_register('myAutoloader');
function myAutoloader($className) { //$classname is 'Folder\Test'
 echo $className.'<br/>';
 include __DIR__ .'\\'.$className.'.php';
}
X::show(); //spl_autoload_register will be invoked due to this line.
Notice: myAutoloader will be invoked when you extend or create any object with new keyword.

& operator

Use 1: Single & is a bitwise AND operator.

Bitwise AND

( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

Use 2: & operator before variable or function means Reference.

Example-1
$array = array(1, 2);
foreach ($array as $value) {
    $value++;
}
print_r($array); // 1, 2 because we iterated over copy of value

foreach ($array as &$value) {
    $value++;
}
print_r($array); // 2, 3 because we iterated over references to actual values of array
Example-2: Only variable can be passed by reference
function show(&$x) {
	echo $x;
}
show(5); //Generates error

Note: In PHP, variable is passed by reference using & operator but in JavaScript object and array is passed by reference automatically.

Aptitude Test

  1. A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
    $x = 5;
    
    function show() { echo $x;}; //Undefined variable $x
    
    echo show();
  2. GET vs Post:
    GETPOST
    GET method is used for requesting data from a specified resource.POST is used for sending the data to the server as a package in a separate communication with the processing script.
    Data is sent in the form of URL parameters which are strings of name-value pairs separated by ampersands(&)Data sent through the POST method will not be seen in the URL
    GET method cannot be used for sending binary data like images or word documentsThe POST method can be used to send ASCII as well as binary data like images and word documents
    This method must not be used if you have any sensitive information like a password to be sent to the server.Sensitive information can be sent using this method.
    It can be used for submitting the form where the user can bookmark the result.Submissions by form with POST cannot be bookmarked.
    You can use this method only for data that is not secure.Data sent through this method is secure.
    GET method is not safer since parameters may be stored in web server logs or browser history.POST method is safer than GET because the parameters are not stored in web server logs or browser history.
  3. Program:
    $x = 8;
    $y = 8.0;
    $z = 8;
    echo ($x === $y); //Displays empty/Nothing
    echo ($x === $z); //Displays 1

    Note: If condition is true PHP returns 1 otherwise PHP returns empty/nothing.

  4. Staick variable scope:
    function myTest() {
      static $x = 0;
      echo $x;
      $x++;
    }

    myTest(); //0
    myTest(); //1
    myTest(); //2

  5. Common ways to write PHP code:
    <?php [   ---  PHP code---- ] ?>
    and
    <? [---  PHP code  ---] ?>
  6. Use of Short tag <?=:
    <?=
    $username = "Onbiponi";
    ?>
    Output:
    Onbiponi
  7. How can you pass a variable by reference?
    Answer: To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2
  8. Will a comparison of an integer 12 and a string “13” work in PHP?
    Answer: “13” and 12 can be compared in PHP since it casts everything to the integer type.
  9. Program:
    <?php
        function uppercase($string)
        {
            echo ucwords($string);
        }
        $wow = "uppercase";
        $wow("Time to live king size");
    ?>
    Output:
    Time To Live King Size
  10. Program:
    <?php
        function TV($string)
        {
            echo "my favourite TV show is ".$string;
            function b()
            {
                echo " I am here to spoil this code";
            }
        }
        function b()
        {
            echo " I am here to spoil this code";
        }
        b();
        TV("Sherlock");
    ?>
    Output:
    Error: function b declared twice

$obj->x() vs array($obj, 'x')

  class MyClass {
    public function x() {
        echo "Method x() called\n";
    }
  }

  $obj = new MyClass();

  // Direct method call
  $obj->x();  // Output: Method x() called

  // Using array to call the method
  $callable = array($obj, 'x');
  $callable();  // Output: Method x() called

So, $obj->x() - directly calls the method. But array($obj, 'x') does not. It creates reference and used to pass it as parameter to a function

Labels: ,

© copyright-2020 Rejaul