PHP $this variable

wordpressquestion picture wordpressquestion · Mar 31, 2011 · Viewed 66.1k times · Source

I am reading some PHP code that I could not understand:

class foo {
  function select($p1, $dbh=null) {
    if ( is_null($dbh) )
        $dbh = $this->dbh ; 
    return; 
  }

  function get() {
    return $this->dbh; 
  }
}

I can't find $this->dbh ($dbh) declaration from the class. My questions are:

  • What is the value of $this->dbh ?

  • Is it a local variable for function select()?

  • Does $this belong class foo's data member? Why is there no declaration for $dbh in this class?

Answer

wordpressquestion picture wordpressquestion · Mar 31, 2011

PHP is not strict for declaration. $this->dbh is a class member. I did the following code to understand the concept:

class foo {

 function foo(){
     $this->dbh = "initial value"; 
 }

 function select($p1, $dbh=null) {
    if ( is_null($dbh) )
        $dbh = $this->dbh ; 
    return; 
 }

 function get() {
     return $this->dbh; 
 }

}

It is same as:

class foo {
  var $dbh = "initial value"; 

  function select($p1, $dbh=null) {
    if ( is_null($dbh) )
       $dbh = $this->dbh ; 
    return; 
  }

  function get() {
     return $this->dbh; 
  }

}