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
PHP is not strict about requiring class property declarations.
E_STRICT
is enabled.NULL
class foo {
function select($p1, $dbh=null) {
if ( is_null($dbh) )
$this->dbh = $dbh ;
return;
}
function get() {
return $this->dbh;
}
}
PHP doesn't force you to declare you class properties but will create them for you when first accessed. Whether this is good or bad, be that as it may, welcome to PHP.
Another thing to check is that you don't have any inheritance happening. Was your $dbh
property defined in a parent class? There isn't anything in the simple code you posted but I can imagine that you simplified a bit for public consumption. :-)
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;
}
}
What is the value of $this->dbh
It will have the default value, if assigned else "null"
Is it a local variable for function select()? If it is, then why get() function can use this variable?
It is the property of foo class, not the local variable, so it will be available to all the methods of the foo class
Does it belongs class foo's data member? If it is, why there is no declaration for $dbh in this class?
Yes it does belong to the foo's data member, you don't see any declaration because, PHP is not strict about requiring class property declarations.
$this->dbh
is.$dbh
is a property of the current object. $this
is use to access to the members of the current object.$this->dbh
can be used in any function inside the class.