OOP - $this variable and self

Posted under » PHP » Methodology on 13 March 2009

$this variable is used inside a class, generally within the member functions to access non-static members of a class (variables or functions) for the current object. You will see this symbol >

class A
{
   function foo()
   {
       if (isset($this)) {
           echo '$this is defined (';
           echo get_class($this);
           echo ")\n";
       } else {
           echo "\$this is not defined.\n";
       }
   }
}

class B
{
   function bar()
   {
       A::foo();
   }
}

$a = new A();
$a->foo();
A::foo();

$b = new B();
$b->bar();
B::bar();

The above example will output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.

ing self for static Class Members

Instead of $this, for static class members (variables or functions), we use self, along with scope resolution operator ::. Let's take an example.

<¿php
 class Job {
             // opening for position
   public $name;
             // description for the job;
   public $desc;
             // company name - as the company name stays the same
   public static $company;          
             // public function to get job name
   public function getName() {
                 return $this->name;
        }
        
        // public function to get job description
   public function getDesc() {
            return $this->desc;
        }
        
        // static function to get the company name
   public static function getCompany() {
            return self::$company;
        }
        
        // non-static function to get the company name
    public function getCompany_nonStatic() {
            return self::getCompany();
        }
    }
    $objJob = new Job();
    // setting values to non-static variables
    $objJob->name = "Data Scientist";
    $objJob->desc = "You must know Data Science";    
    /* 
        setting value for static variable.
        done using the class name
    */
    Job::$company = "anoneh";
    
    // calling the methods
    echo "Job Name: " .$objJob->getName()."
"; echo "Job Description: " .$objJob->getDesc()."
"; echo "Company Name: " .Job::getCompany_nonStatic(); ?>

PHP self refers to the class members, but not for any particular object. This is because the static members (variables or functions) are class members shared by all the objects of the class. It doesn't require a $ but a :: (scope resolution operator).

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data