Category Archives: OOPS Concepts

PHP Traits

One of the problem of PHP as a OOP language is, the fact that you can only have single inheritance. This means your class can only inherit from one other class.

 

PHP Traits (new feature was added in PHP 5.4) is kind of like a Mixin, allows you to mix Trait classes into an existing class. This means you can reduce code duplication and get the benefits whilst avoiding the problems of multiple inheritance.

 

As per the PHP Documentation, a Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

 

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

 

Let’s take some example to make more clear about Traits.

 

A trait is similar to an abstract class which cannot be instantiated on its own (though more often it’s compared to an interface).


<?php

trait Helloworld
{
      private $message;

      function sayHello() {
        echo "Hello";
      }

      function sayWorld() {
       echo "World";
      }

      abstract function define();
}

?>

It can have functions, data members, abstract function etc same as class you have.

 

PHP have some set of rules defined to use Traits in his best way like Precedence, Use of Multiple Traits, Conflict Resolution, Method Visibility etc.

To understand the Traits and how these can be used to make your life easy, I have googled and found some very good example/posts with explanation that will really help you.

 

One is PHP Documents itself (Bible for all PHP Developers)
http://php.net/manual/en/language.oop5.traits.php

 

Second one is found on SitePoint
http://www.sitepoint.com/using-traits-in-php-5-4/

 

Hope these will helps!!

 

Benefits of Traits

  1. Traits reduce your code duplication whilst preventing complicated class inheritance that might not make sense within the context of your application.
  2. It allows you to define simple clear and concise code and then mix in that functionality wherever needed.
  3. It somehow reduce the situation as generally possible in the multiple inheritance supporting languages called as “Diamond Problem“.

Drawbacks of Traits

  1. Entire class abilities are NOT in one location visually.
  2. You alter the trait thinking it will alter one type of class using it, but may introduce problems in another class also using it. Meaning you will have to know all classes using the trait.
  3. Introduces the idea of multiple inheritance, which bring with it the need to worry about conflicts in naming. (Yes you can solve it using insteadof, but now you have to worry about that and take precautions like specific naming related to the trait or to use this keyword).

Conclusion

So now after have a look on all features and benefits and drawback now a question is, Should you use Traits?
You should, as Traits allow you to create cleaner, simpler, and more efficient code fragments horizontally across multiple classes which do not have to be within the same inheritance hierarchy.

As a developer we have some bad or good situation for all code and logic, so it is your choice how will you play with Traits?

PHP Object cloning using clone keyword and __clone() magic method

Object cloning or clone of an object means to create a duplicate of an object.
With regular variables $var1 = $var2 means that a new variable $var1 created and have the value of $var2 that means 2 variables created.

 

With objects $obj2 = $obj1 does not mean that a new object i.e. $obj2 get created.

 

When we execute $obj2 = $obj1, the reference of $obj1 is assigned to $obj2. This means that $obj1 and $obj2 point to the same memory space.

So assigning other variables to an object will not actually copy the object, it will simply create a new reference to the same object. In order to truly copy an object, we must use the clone keyword.

<?php

class House {
	private $room_name;
 
	public function setRoomName($room_name) {
		$this->room_name = $room_name;
	}
 
	public function getRoomName() {
		return $this->room_name;
	}
}
 
$obj1 = new House();
$obj1->setRoomName("Bedroom");
 
$obj2 = $obj1; //only reference or memory assigned
 
$obj2->setRoomName("Dining Room");
 
echo $obj1->getRoomName();
echo $obj2->getRoomName();

?>

Both will return “Bedroom”

Therefore, to create a new $obj2 object we must “clone” an object to create a new object.

<?php
	$obj2 = clone $obj1;
?>

 

After the above line is executed $obj2 with a new memory space is created with the data members having the same value as that of $obj1. This is also referred to as shallow copy.

 

However, this technique will not work with a class that has a data member which is an object of another class (i.e object of an object technique is used). In such a scenario, the cloned object continues to share the reference of the data member object of the class that was cloned.

 

For resolving this we need to use the concept of ‘deep copy’ as opposed to ‘shallow copy’. To implement this you should implement the magic method __clone().

<?php

class House {
	private $room_name;
 
	public function setRoomName($room_name) {
		$this->room_name = $room_name;
	}
 
	public function getRoomName() {
		return $this->room_name;
	}
 
	public function __clone() {
		$obj = new House();
		$obj->setRoomName($this->room_name);
		return $obj;
	}
 
}
 
$obj1 = new House();
$obj1->setRoomName("Bedroom");
 
$obj2 = clone $obj1; //new object $obj2
 
$obj2->setRoomName("Dining Room");
 
echo $obj1->getRoomName();
echo $obj2->getRoomName();

?>

 

So, the __clone() magic method allows developers to implement a deep copy of an object when it is cloned.

PHP first performs a shallow clone and the calls the __clone() method on the new object, if it exists, to complete the cloning process.

 

PHP Magic Predefined Constants & usages

PHP Magic Predefined Constants & usages

In PHP, a constant is a name or an identifier for a simple value. A constant name starts with a letter or underscore can be followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

 

You have to use define() function to put value in the constant and for retrieval the value simply specifying the name.
The constant() function can be used if you create the constant name dynamically and want to fetch the value of the constant.

 

<?php
define("SITENAME", 'scriptarticle.com');
echo SITENAME;
echo constant("SITENAME"); // returns the same as previous one
?>

 

Along with the above PHP itself have a lot of predefined constants.

Some of the constants that are specials and can be called as magical are listed as below with example, these starts and ends with double underscore (__) and written in capital letters.

The predefined constants are very useful to access information about your code.

 

__LINE__

returns the line number in the code where the constant appears.

 

__DIR__

represents the path to the current file.

 

__CLASS__

returns current class name.

 

__FUNCTION__

returns current function name.

 

__METHOD__

represents the current method name.

 

__NAMESPACE__

returns the current namespace name.

 

__FILE__

represents the name of your file, includes its full path.

 

I have included all these in the below example, have a look.

<?php

	// Set namespace (works only with PHP 5.3 and later)
	namespace Scriptarticle;

	// this echo current file's full path and name
	echo "This file full path and file name is '" . __FILE__;

	// this echo file full path
	echo "This file full path is '" . __DIR__;

	// This echo current line number on file
	echo "This is line number " . __LINE__;

	function function_magic_constant() {
		echo "This is from '" . __FUNCTION__ . "' function.";
	}

	// echo function and used namespace
	function_magic_constant();

	class SAConstants {
		// echo class name
		public function printClassName() {
			echo "This is " . __CLASS__ . " class";
		}
		// echo class and method name
		public function printMethodName() {
			echo "This is " . __METHOD__ . " method";
		}
		// echo function name
		public function printFunction() {
			echo "This is function '" . __FUNCTION__ . "' inside class";
		}
		public function printNamespace() {
			echo "Namespace name is '" . __NAMESPACE__ . "'";
		}
	}

	// create a object of the class
	$obj = new SAConstants;

	$obj->printClassName();

	$obj->printMethodName();

	// this prints function name inside class and used namespace
	// same as method name, but without class
	$obj->printFunction();

	// this prints namespace name
	$obj->printNamespace();

?>

 

If you want to view a complete list of PHP predefined constant then follow the below links.

PHP Config Predefined Constants
PHP Image Predefined Constants
PHP Date Predefined Constants
PHP Core Predefined Constants
PHP Magic constants

 

Hope you have enjoyed the post!!

 

A Quick view on PHP magic methods

Magic Methods in PHP

(PHP Magical Reserved Functions Starts with double underscore)

According to me you all have heard about the PHP Magic methods.
You have also used some of these like __autoload and __construct.

 

Let’s have a quick view on magic methods, as sometimes it looks like it will hard to use these function but reality is these are very simple.
First of all let me tell what magic method is and why these are called magical? Are these methods really showed some type of magic as the name imply.

 

PHP reserves all function names starting with two underscore prefix (__) as magical.

Magic methods provide hooks into special PHP behavior.

 

PHP does not provide the definitions of the magic functions and the programmers have to write/code that what these functions will do. Magic functions will never directly be called by the programmer but PHP will call the function ‘behind the scenes’. That’s why they are called ‘magic’ functions because these can not be directly called and they allow the programmer to do some powerful things by the coding. I think it’s enough; you will be clearer by examples.

 

__autoload()
This is not a magic method exactly but it is very useful. The __autoload() function is automatically called when a class is instantiated and file will get include in the code. This is useful since you don’t always want to load every class again and again and add just in case you need it to add.

 

__construct()
This magic methods is called when user create object (instances of your class) of the class. Usually this is used for creating constructor in php5.

 

__destruct()
As the name implies, the __destruct() method is called when the object is destroyed by PHP’s garbage collector. It accepts no arguments, and it is usually used to perform memory clean-up operations such as closing a database connection or closing any file.

<?php

class House{

  public function __construct() {
    $this->created = time();
    $this->logfile = fopen('/tmp/log.txt', 'w');
  }

  public function __destruct() {
    fclose($this->logfile);
  }
}
$home = new House;
echo $home->created;
?>

 

__get
This method is called when your object try attempt to read property or variable of the class which is unavailable or inaccessible.

 

__set
This method called when object of your class attempts to set value of the property which is inaccessible or unavailable in your class.

 

__call
This magic method trigger when you are attempting to call method or function of the class which is either inaccessible or unavailable.

 

__callstatic
This is same as __call executes when inaccessible or unavailable method in static context.

<?php

class House
{
    function __get($name)
    {
        echo "__get executed as $name is unavailable";
    }
    function __set($name , $value)
    {
        echo "__set executed as $name not exists or inaccessible";
    }
    function __call($name , $parameter)
    {
        $a = print_r($parameter , true); //taking recursive array in string
        echo "__call executed with name $name , parameter $a";

    }
    static function __callStatic($name , $parameter)
    {
        $a = print_r($parameter , true); //taking recursive array in string
        echo "__callStatic executed with name $name , parameter $a";

    }
}
$a = new House();
$a->abc = 3;//__set executed
$app =  $a->myvar;//__get triggerd
$a->getMyinfo('mahesh' , 'scriptarticle', 'blog');//__call willl executed
House::xyz('1' , 'sca' , 'help');//__callstatic will executed

?>

 

__isset
This magic methods called when isset() function is applied on a property of the class which is inaccessible or unavailable.

 

__unset
This is just opposite of isset method as it called when unset() function called on inaccessible or unavailable property of the class.

<?php

class House
{
  function __isset($name)
  {
      echo "__isset is called for $name is unavailable";
  }
  function __unset($name)
  {
      echo "__unset is called for $name";
  }
}
$a = new House();
isset($a->myvar);
unset($a->yourvar);

?>

 

__sleep
This method will trigger when you are going to serialize your class’s object.

__wakeup
This will execute when you are un-serializing any class object.

<?php

class House {
    public $name;
    public $width;
    public $data = array(); // stores misc. data in an array
    public $connection;     // holds some connection resource  

    public function  __sleep() {
        // list the properties to save
        return array('name', '56', 'data');
    }  

    public function  __wakeup() {
        // reconnect to the house
        $this->connect();
    }
}
?>

 

__toString
This executes when you are using echo on your object.

__invoke
This will trigger when you are using object of your class as function.

<?php

class House
{
    public $myvar;

    public function __construct($myvar)
    {
        $this->myvar = $myvar;
    }

    public function __toString()
    {
        return $this->myvar;
    }

	public function __invoke($x)
    {
        var_dump($x);
    }
}

$object = new House('Hello');
echo $object; // __toString will called
$object(8); // __invoke called
?>

 

I have still left some magic methods as __clone(),__set_state() I’ll post a new article for these very soon.

Hope the above one helps you a lot.

 

Search Engine Spider and User Agent Identification with “Ultimate User Agent Blacklist”

Search Engine Spider and User Agent Identification with “Ultimate User Agent Blacklist”

 

A user-agent is software (a software agent) that is acting on behalf of a user.
In many cases, a user-agent acts as a client in a network protocol used in communications within a client–server distributed computing system.

 

For more information view wiki
http://en.wikipedia.org/wiki/User_agent

 

Automated Agents is called as Bots.
http://user-agents.org has a complete list of all latest spiders/bots/user agents.
There are some more and those are anonymous (not known and have very different names).

 

If you develop a website and want to make the site accessible by some specific user agent or bots of a country, then you can update the information in your root .htaccess file.

 

As, Bot blocking blacklists are useless in some way as some rogue spiders just generate random user-agent strings so we will never have them in our list to start with, but We have tried list out as much as we can in the below zip file.

 

Ultimate User Agent Blacklist

 

What you have to done is, unzip the file and paste the code in your root .htaccess file, it will protect your website from unwanted crawling/indexing by anonymous bots.

 

If your website uses WordPress open-source, then can also use “Better WP Security” plug-in.
Just need to download and install the plug-in and go to “Better WP Security – Ban Users” Tab and enable “Enable Default Banned List”, you can also update the list according to your needs.

 

But please be careful before doing same, as it may affect your website’s core files and plug-in, So before doing this backup your website’s files and database.

 

How to achieve and use Polymorphism in PHP

Polymorphism – the concept

 

Polymorphism is a Greek word that means “many forms”. In object-oriented programming, polymorphism is a mechanism by which objects of different types can process data through a single interface. Using a typical illustrative example, a program might define a type of object called Animal, containing a function called talk() and, through inheritance, derive object sub-types such as Cat, Dog, etc. that each have their own specific implementation of the talk() function. The mechanism of polymorphism allows such a program to call the talk() function without actually knowing whether it is calling it for a Cat, Dog, or any other derivative Animal, while executing the correct function for the specific type of Animal.

 

Why method polymorphism cannot be achieved in PHP?
In languages like Java where in a function sum (int, int) differs from sum (float, float), the method sum() has many forms depending on the parameters being passed to it.

But in PHP it is not possible because you can have a method that accepts two parameters and call it by passing three parameters (allows variable arguments). This is because PHP is not strict and contains methods like func_num_args() and func_get_arg() to find the number of arguments passed and get a particular parameter.

 

Polymorphism is not the same as method overloading or method overriding (in OOP, a method is a function that belongs to a class, while the class variables are referred to as its members) and should not be confused with these.

 

Method overloading is where a class has two or more functions of the same name, but accepting a different number and/or data types of parameters.

 

Method overriding is where a child class (one derived through inheritance) defines a function with the same name and parameters as a function in its parent class, but provides a different implementation of the function. This is not the same as polymorphism, as it does not necessarily involve late-binding, however overriding is part of the mechanism by which polymorphism is accomplished.

 

 

PHP 5 & Polymorphism
Since PHP 5 introduces the concept of Type Hinting, polymorphism is possible with class methods. The basis of polymorphism is Inheritance and overridden methods.


<?php

class BaseClass {
 public function myMethod() {
 echo "BaseClass method called";
 }
}

class DerivedClass extends BaseClass {
 public function myMethod() {
 echo "DerivedClass method called";
 }
}

function processClass(BaseClass $c) {
 $c->myMethod();
}

$c = new DerivedClass();
processClass($c);

?>

 

OUTPUT:

DerivedClass method called

 

In the above example, object $c of class DerievedClass is executed and passed to the processClass() method. The parameter accepted in processClass() is that of BaseClass. Within the processClass() the method myMethod() is being called. Since the method is being called on the class variable of BaseClass, it would not be wrong to assume that myMethod() of class BaseClass will be called. But, as per the definition “When the decision to invoke a function call is made by inspecting the object at runtime it is called Polymorphism”, myMethod() will be called on object DerievedClass. The reason why this happens is because the object of DerievedClass is being passed and hence the method myMethod() of DerievedClass will be called.

 

I hope the above makes sense and hasn’t been too confusing as you know this is difficult to explain in clear English 🙁