PHP $这个变量

wor*_*ion 26 php variables global local

我正在阅读一些我无法理解的PHP代码:

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

  function get() {
    return $this->dbh; 
  }
}
Run Code Online (Sandbox Code Playgroud)

我找不到$this->dbh ($dbh)课堂上的声明.我的问题是:

  • 有什么价值$this->dbh

  • 它是函数的局部变量select()吗?

  • 是否$this属于class foo"s的数据成员?为什么$dbh这堂课没有声明?

wor*_*ion 22

PHP对声明并不严格.$ this-> dbh是一个类成员.我做了以下代码来理解这个概念:

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; 
 }

}
Run Code Online (Sandbox Code Playgroud)

它与:

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

  • 扎实的解释+1 :) (3认同)
  • 很高兴,你很高兴:) (2认同)

Uns*_*ned 18

PHP对要求类属性声明并不严格.

  • 分配时,将静默创建该属性.
  • 如果E_STRICT已启用,则从不存在的属性读取会生成通知.
  • 任何未定义属性的默认值为 NULL