Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP $this variable

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?

like image 573
wordpressquestion Avatar asked Mar 31 '11 01:03

wordpressquestion


People also ask

Can we use $this as variable in PHP?

$this – a pseudo-variable: Unlike other reserved keywords used in the context of class like the static, parent, etc does not need to be declared with the dollar sign ('$'). This is because in PHP $this is treated as a pseudo-variable.

Can we increment static variable in PHP?

The increment_counter() function will increment the value of the static variable by 1. The self keyword is used in the script to read and increment the value of the static variable. echo $object->increment_counter()."

What is the use of this -> in PHP?

The object operator, -> , is used in object scope to access methods and properties of an object. It's meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator.

What is PHP and $$ variables?

PHP $ and $$ Variables. The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc. The $$var (double dollar) is a reference variable that stores the value of the $variable inside it.


1 Answers

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;    }  } 
like image 133
wordpressquestion Avatar answered Oct 05 '22 10:10

wordpressquestion