BlogsTechnology

Confusing Elements of PHP OOP

SHARES
ShareTweet

After the introduction of object oriented approach in PHP, many keywords are being used in programming PHP applications. Few of them are straight forward as any other language and few others are just confusing. Today I am going to discuss such confusing elements of PHP OOP. Following is a quick list on what you find in this post.

  • $this
  • self::
  • parent::
  • static::

$this Operator in PHP

It is used to access the properties and methods of the same class inside a method.

Example:

class example1
{
public $name = "Sachin";
public function ShowName()
    {
      echo “ The Name is :  “.  $this->$name;
    }
}

The self:: operator

This is same as that of $this with a small difference. It is used to access propertis and methods in cases where both of them are declared with static keyword.

Example :

class StaticExample {
static public $aNum = 0;
static public function sayHello()
    {
     self::$aNum++;
     print "hello (".self::$aNum.")n";
    }
}

The parent:: operator

Now this is used in context of inheritance. Say a class inherits another and also inherited class overload one of the function of in inheriting class .Then if your inherited class has to call a function from an inheriting class , we use parent::

Example:

class one
{
public $name = "Sachin";
public function ShowName()
   {
     echo “ The Name is :  “.  $this->$name;
    }
}

class two extends one
{

public function ShowName()
  {
    parent::ShowName();
  }

}

Static:: Operator

Again this is used in the context of inheritance.Say a class A has a constructor which call the function show() of the same class where the constructor is defined. Now The class B inherits the class A and also has a constructor.

Say the class B also a function by name show() (function overloading). Now if you want to call the function of respective class on object creation we use static::

Example:

abstract class DomainObject
{

private $group;

public function __construct()  {
      $this->group = static::getGroup();
    }

public static function create() { return new static(); }

static function getGroup() { return "default"; }
}

class User extends DomainObject
{

}

class Document extends DomainObject
{
  static function getGroup() { return "document"; }
}

class SpreadSheet extends Document
{

}

print_r(User::create());
print_r(SpreadSheet::create());